<?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 Prashant Kumar on Medium]]></title>
        <description><![CDATA[Stories by Prashant Kumar on Medium]]></description>
        <link>https://medium.com/@prashantx7979?source=rss-91a262276cf5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bKpnB2-w8o0-4yRDkTOruA.jpeg</url>
            <title>Stories by Prashant Kumar on Medium</title>
            <link>https://medium.com/@prashantx7979?source=rss-91a262276cf5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:13:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashantx7979/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[How to Design Memory for a Multi-Agent System]]></title>
            <link>https://medium.com/@prashantx7979/how-to-design-memory-for-a-multi-agent-system-7a7545d636eb?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a7545d636eb</guid>
            <category><![CDATA[langraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 04:21:10 GMT</pubDate>
            <atom:updated>2026-09-14T04:21:10.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IYPURNEE1ZfpfLHD" /></figure><p>A story about four agents, one question, and the difficulty of maintaining one shared reality.</p><p>If you read the earlier piece on single-agent memory, you already know the basic problem: one agent needs to remember things across time, or it repeats work it already finished. Put four agents on the same job, and you get that problem plus a second one stacked on top of it. It’s not enough for each agent to remember its own past — they also have to stay on the same page as each other while working at the same time. That second problem is what this piece is actually about.</p><h3>Four agents walk into the same problem</h3><p>Say a bank wants to make digital banking easier for customers in rural areas. The question sounds simple:</p><p>How should digital banking become more accessible to rural users?</p><p>But the answer touches several different problems at once — how people actually use the app, whether the technology holds up, whether it’s safe, whether the evidence is solid. So instead of handing the whole question to one big agent, the bank sets up a small team: a <strong>Customer Agent</strong> looking into what’s actually hard for rural users, a <strong>Technology Agent</strong> checking whether things like voice interfaces are reliable enough, a <strong>Risk Agent</strong> looking at security and regulation, a <strong>Citation Agent</strong> making sure every claim has real evidence behind it, and a <strong>Lead Researcher</strong> pulling it all together.</p><p>Each agent is capable, each has a clear job, and they can message each other. On paper, this looks completely fine.</p><p>Then they actually start working.</p><p>The Customer Agent comes back with: voice-first navigation could make things much easier for people who struggle with text-heavy apps. The Technology Agent comes back with: voice recognition gets unreliable in noisy environments and across different accents. The Risk Agent comes back with: voice alone isn’t safe enough for sensitive transactions. The Citation Agent flags that a couple of the bigger claims still don’t have strong evidence behind them.</p><p>None of this is wrong. Each agent is right about the slice of the problem it looked at. The trouble is that every agent only sees one slice. Everyone knows something. Nobody knows everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XLUJQE8VP5W0LxE2" /></figure><p>That’s exactly where multi-agent memory starts. Not with a vector database, not with embeddings, not with a new framework — with a much plainer question: how do four agents working in parallel end up with one shared, coherent understanding of the work, instead of four separate ones?</p><h3>One agent remembering is different from four agents agreeing</h3><p>A single agent mostly needs to remember across time: what did I already try, what happened last time, what should I do next. A team of agents needs that too, plus something extra: staying consistent with each other while working in parallel. What has the team found so far? Who found it? Which parts are solid, and which are still shaky? What happens when two agents land on different answers?</p><p>This isn’t a hypothetical worry. Researchers who traced over 1,600 real multi-agent runs across several popular frameworks found that more than a third of all failures came down to agents simply being out of sync with each other — duplicating work, contradicting each other, or acting on something another agent had already ruled out. That’s not a model-quality problem you fix with a better model. It’s a structural gap, and it’s exactly the gap this piece is about closing.</p><h3>Sending a message isn’t the same as remembering something</h3><p>The agents in our story can already talk to each other. The Customer Agent can tell the Lead Researcher “voice access might help with literacy barriers,” and the Lead Researcher can pass that along to the Technology Agent. That solves the problem of the moment. It doesn’t solve much else.</p><p>A message like that doesn’t automatically survive if the conversation gets trimmed down to save space. It doesn’t automatically reach an agent that gets spun up later in the process. It doesn’t keep track of where the claim came from, so nobody can double-check it afterward. And it doesn’t get corrected if someone finds out later that it was wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5C4O4w7hRqCzFDbP" /></figure><p>Passing a message around is useful right now and easy to lose later. What you actually want is something closer to writing the finding down somewhere everyone can come back to, with where it came from attached, so it doesn’t just evaporate once the conversation moves on.</p><h3>So what should the team actually write down?</h3><p>The obvious answer is “everything — just put it all in one shared pool, and now every agent can see everything.” That sounds like it solves the problem. It doesn’t.</p><p>Picture the Technology Agent’s actual working notes: twenty searches that went nowhere, a few hypotheses it later dropped, sources it decided weren’t good enough, half-finished thoughts. Does the Risk Agent need any of that? No. If everything becomes shared, the team ends up with more information and less clarity — agents burn time and tokens reading each other’s leftovers, and half-formed guesses start looking like settled facts just because they’re sitting in the shared pool next to real findings.</p><p>So instead of one big pile, it helps to think in three levels, based on who actually needs to see something.</p><p><strong>What I need</strong> stays private, with one agent. For the Technology Agent, that’s the searches it already tried, the sources it rejected, whatever it’s currently working through. None of that needs to leave its own workspace. Keeping it private isn’t about secrecy — it’s about not making everyone else wade through your rough drafts.</p><p><strong>What we need</strong> is the shared layer, holding only what the team needs to coordinate: the research goal, findings solid enough to share, important sources, open questions, and places where agents disagree. The Customer Agent can post “voice-first navigation may help — needs a technology and risk review” without dumping its entire research trail into the shared space.</p><p><strong>What the system needs</strong> sits above even the team — standing rules that apply across every research job the bank ever runs, not just this one. Things like “always prefer primary sources,” “every important claim needs evidence,” “never store personal customer data.” These aren’t findings from this task. They’re the ground rules everyone operates under, every time.</p><h3>The picture worth remembering</h3><p>Put those three levels together and you get a simple shape: agents keep their own notes privately, promote the important stuff up to a shared space, and the team’s conclusions eventually feed into one official record of where things currently stand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fQZQqmcm7WJxdxcz" /></figure><p>That last part matters more than it looks like it should, and it’s worth being precise about, because “memory,” “state,” and “the rules everyone follows” are actually three different questions, even though they get drawn as one stack above. <strong>Memory</strong> answers what should we retain and be able to retrieve. <strong>State</strong> answers what’s the current status of the actual work. <strong>Policy</strong> answers what standing rules govern how the system behaves. The three private/shared/application boxes above are really two of those (memory, and the cross-cutting policy layer); the official-record box at the bottom is the third, and it’s a genuinely different kind of thing, not just a bigger memory store.</p><p>Concretely: the shared layer might say “the Customer Agent thinks voice-first navigation looks promising.” That’s a finding — someone’s conclusion. The official record might still say research_status = under_review. The first is memory. The second is state. <strong>Each layer needs less information than the one below it — that’s what makes coordination affordable instead of expensive.</strong> Agents contribute what they’ve found. The system decides what’s actually official.</p><h3>What a shared finding actually looks like</h3><p>It’s easy to talk about “findings” in the abstract. In practice, a finding worth sharing needs a bit more structure than a single sentence, or you lose the ability to check it later. Here’s roughly what one looks like once it’s written down properly:</p><p>Nothing exotic here — task_id keeps this finding from bleeding into an unrelated job, created_by is where it came from, evidence is what backs it up, visibility controls who can see it, and status stops an unverified guess from quietly being treated as settled fact. That last field is doing more work than it looks like — it’s the difference between a hunch and a conclusion, and it’s the field that gets checked before anything downstream trusts this finding.</p><h3>But where should that memory actually live?</h3><p>Knowing what’s private, shared, and standing policy is only half the design. The other half is architectural: where does the shared part physically sit?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5noWwDePMy9eypRK" /></figure><p>Think of it as three ways a team could organize a shared notebook. <strong>One whiteboard</strong> — everyone writes to the same shared space. Easy to reason about, easy to debug, exactly one place to check. It also gets crowded fast: agents see things that have nothing to do with their job, two updates at once can collide, and as the team grows, that one shared board becomes the thing everyone’s waiting on.</p><p><strong>Everyone keeps their own notebook</strong> — each agent holds its own memory, sharing specific things only when it matters. Agents stay specialized and nothing irrelevant piles up, but when one agent’s notebook changes, the others don’t automatically find out, so someone can end up working off information that’s already stale.</p><p><strong>Private notebooks, plus one shared whiteboard</strong> — each agent thinks privately, and only what matters for the team gets promoted to a shared space. This is the one that fits our banking team best, and for good reason: one engineer who’s built a number of these systems has written that most of what he’s shipped eventually lands here, because most teams genuinely need both a place for global coordination and room for a specialist to keep private context — not one or the other.</p><p>None of these trade-offs actually disappear, they just move around. Push for stronger consistency and you generally pay in speed — more checking, more waiting for agents to agree. Push for speed and you usually relax how up-to-date everything is, which is exactly how one agent ends up acting on a fact another agent already corrected. That tension doesn’t go away with a clever architecture. It just gets placed wherever hurts least for your specific system.</p><h3>Seeing the wiring, concretely</h3><p>Everything above is still fairly conceptual. If you’re the kind of engineer who wants to see where each box would actually live in a real system, here’s one reasonable way to wire it together for the banking example:</p><p>A request comes in, the Lead Researcher plans the work, and a Task Orchestrator hands pieces to each specialist agent. Each specialist reads and writes to its own slice of a Memory Service, which is really three separate stores behind one interface: private memory per agent, shared task memory for the team, and application memory for the standing rules that don’t change between runs. Findings that get promoted flow into a State Store — the official record — which the Lead Researcher reads back from when it’s time to synthesize a final answer. None of the specialist agents write to the State Store directly. Only the synthesis step does, and only after checking with the Citation Agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dQqF5NFkRhBijgSv" /></figure><p>That last constraint is the one worth not skipping, even though it looks like a formality on a diagram.</p><h3>Then the agents actually disagree — and memory has to explain why</h3><p>The team has private notes and a shared whiteboard. It looks like the design is done. Then this happens.</p><p>The Customer Agent writes: voice-first navigation could help users who find text-heavy apps difficult. The Technology Agent writes: voice recognition gets unreliable in noisy environments. The Risk Agent writes: voice alone isn’t safe enough for sensitive transactions.</p><p>So — who’s right? Probably all three. They’re not actually contradicting each other; each is describing a different slice of the same problem — ease of use, reliability, security. A weak system looks at three different-sounding statements and assumes it has to pick one and throw the rest away. A better one asks a simpler question first: where did each of these come from, and what part of the problem does each one actually cover?</p><p>That’s exactly what the fields in the finding above are for — who made it, what backs it up, what it actually covers, how sure the team is, whether anyone’s double-checked it. Once that’s attached, the three statements above stop looking like a conflict and start looking like three compatible inputs to one synthesis: use voice-first navigation for everyday tasks, add a simple fallback for when voice isn’t reliable, and require stronger verification for sensitive transactions. All three original findings survive, each doing the job it was actually good for.</p><p><strong>Good shared memory doesn’t erase disagreement. It keeps enough context around each finding that disagreement turns into useful information instead of noise.</strong> Without that, you’d have had to just pick one agent’s answer and quietly ignore the other two.</p><h3>When memory goes stale</h3><p>Here’s a failure worth walking through directly, because it’s the one that shows up in production more than any of the others.</p><p>Early in the research, the Technology Agent tests voice recognition and stores a finding: accuracy looks acceptable. Two days later, a more thorough test turns up serious problems in noisy environments — the kind of environment plenty of rural customers will actually be in. But the Risk Agent, working slightly ahead of that update, retrieves the old finding and factors “acceptable accuracy” into its recommendation. The Lead Researcher never sees the correction, because nothing ever told it there was one.</p><p>The fix isn’t complicated, but it has to be designed in on purpose — it doesn’t happen by accident:</p><p>New evidence arrives → the old finding gets updated, not silently replaced → the previous version stays on record rather than vanishing → anything that already used the stale finding gets flagged → synthesis uses the current version, not whatever happened to be cached in someone’s context.</p><p>That’s four real mechanisms hiding behind one sentence: keeping old versions instead of just overwriting them, noticing when something’s gone stale, telling the agents affected, and making sure the final synthesis always pulls the latest valid answer instead of whatever it grabbed first. Skip any one of them, and a correction some agent made two days ago quietly never reaches the answer at all.</p><h3>Memory still isn’t the same thing as state</h3><p>One distinction has to survive everything above it: what the agents believe and what the system officially considers true are not the same thing, and blurring that line is where a lot of multi-agent systems quietly go wrong.</p><p>The shared memory can — correctly — hold three different agent conclusions at once: voice-first navigation appears promising, voice needs a fallback, sensitive actions need stronger verification. None of that lets any single agent skip ahead. The Customer Agent cannot decide on its own that the final recommendation is “voice-only,” no matter how confident its finding is. The official record stays exactly what the workflow says — research_status = synthesizing, citation_status = pending — until the Lead Researcher has weighed every relevant finding and the Citation Agent has verified the claims that matter.</p><p>Agents contribute evidence. The system decides when that evidence adds up to something final.</p><h3>Putting it all together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*stayzK_p1OmCa_Yt" /></figure><p>The final recommendation that comes out the other end isn’t one agent’s opinion wearing the system’s authority. It’s an actual synthesis: a voice-first interface for navigation and low-risk requests, multilingual support for local accessibility, a keypad or assisted fallback for when voice recognition struggles, and stronger verification on anything sensitive.</p><p>The Customer Agent contributed the accessibility problem. The Technology Agent contributed the feasibility constraints. The Risk Agent contributed the security boundaries. The Citation Agent verified the evidence behind all of it. The Lead Researcher combined four partial views into one recommendation that could actually stand behind its own claims.</p><p>Shared memory didn’t make every agent know everything. It made sure every agent’s real contribution survived long enough to become part of the answer.</p><h3>Five rules worth taking into production</h3><p><strong>Keep private memory private by default.</strong> Not every query, tool result, or abandoned hypothesis needs an audience.</p><p><strong>Share outcomes, not entire histories.</strong> What moves into the shared space should be findings, evidence, and decisions — not a replay of everything an agent tried on the way there.</p><p><strong>Keep memory separate from state.</strong> Agents produce observations. The system — not any single agent — decides when something becomes official.</p><p><strong>Hold onto where each finding came from.</strong> Every shared finding is worth more if you know who made it, what it’s based on, and whether it’s been checked. Losing that context is how disagreements turn into confusion instead of useful information.</p><p><strong>Make disagreement and staleness visible, never silent.</strong> Don’t quietly overwrite one finding with another, and don’t let a corrected finding keep circulating as if nothing changed.</p><h3>The point of all this</h3><p>The Customer Agent needs customer evidence. The Technology Agent needs feasibility findings. The Risk Agent needs security constraints. The Citation Agent needs sources. The Lead Researcher needs a trustworthy summary of all four — not the raw output of all four.</p><p>Private memory gives each agent room to actually think for itself. Shared memory is what lets the team come back together. Knowing where a finding came from is what makes disagreement useful instead of confusing. A clear line between what agents believe and what’s officially true is what stops four honest opinions from turning into four different final answers. And catching a stale finding before it reaches the answer is what keeps all of the above from quietly rotting over time.</p><p>The goal was never for every agent to remember everything. It was for the right pieces to survive long enough to become one answer the team can actually stand behind.</p><p>Have you built something where multiple agents needed to agree on one answer? What actually broke first — the sharing, the disagreements, or knowing which version was official?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a7545d636eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Memory Explained: Working, Episodic, Semantic & Procedural]]></title>
            <link>https://medium.com/@prashantx7979/agent-memory-explained-working-episodic-semantic-procedural-5ff3582f4615?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ff3582f4615</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 02:00:56 GMT</pubDate>
            <atom:updated>2026-09-09T02:00:56.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6isanbC4oH3GWDyt" /></figure><p>My Agent Fixed the Same Bug Twice: The 4 Types of Agent Memory</p><p>Part 3 of 30 in the AI System Design Series</p><p>My agent fixed the same bug twice.</p><p>During the first session, the agent found BUG-142, traced the problem to the migration order, changed the implementation, ran the integration tests, and confirmed that the fix worked.</p><p>Then the session ended.</p><p>To control token usage, my agent harness cleared the conversation history before starting the next session. That was intentional. Replaying an ever-growing transcript would have increased cost, latency, and distraction.</p><p>The problem was that the conversation was not the only thing that disappeared.</p><p>Nothing recorded that the bug had been fixed. The successful test result existed only inside the previous context window. Worse, the task tracker still showed BUG-142 as open.</p><p>When the second session began, the agent saw an open bug and did exactly what the system asked it to do.</p><p>It investigated the issue again.</p><p>It reached the same conclusion.</p><p>And it attempted the same fix.</p><p>The model had not forgotten how to solve the bug.</p><p>The system had failed to preserve that the bug was already solved.</p><p>That incident changed how I think about agent memory.</p><p>The interesting question was no longer:</p><blockquote><em>How do I give my agent memory?</em></blockquote><p>It became:</p><blockquote><em>What kind of information should have survived the session?</em></blockquote><p>That question leads to four different kinds of agent memory:</p><ul><li><strong>Working memory</strong>: What am I doing right now?</li><li><strong>Episodic memory</strong>: What happened?</li><li><strong>Semantic memory</strong>: What do I know?</li><li><strong>Procedural memory</strong>: How should I do it?</li></ul><p><strong>In short:</strong> memory isn’t one thing. It’s at least four different jobs, and most of the failures in this article come from mixing them up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uE_5R7-HerrSpde3" /></figure><p>These categories are influenced by cognitive science and appear in modern frameworks such as Cognitive Architectures for Language Agents, usually called CoALA. CoALA describes language agents through modular memory, structured action spaces, and decision-making processes.</p><p>But before exploring the four types, we need to separate three concepts that are often treated as interchangeable:</p><p>Context, memory, and authoritative state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IGuPyVCRYm4wouJ4" /></figure><h3>Context Is Not Memory</h3><p><strong>In short:</strong> the context window is only what the model can see right now. Nothing guarantees it survives once the conversation clears.</p><p>An agent’s context is everything available to the model during the current inference call.</p><p>That may include:</p><ul><li>System instructions</li><li>Tool definitions</li><li>Recent conversation messages</li><li>Retrieved documents</li><li>Files currently being edited</li><li>Tool outputs</li><li>The current task plan</li></ul><p>Context is the agent’s active workspace. It contains the information the model can use immediately.</p><p>But context is temporary.</p><p>When a session ends, a conversation is compacted, or older messages are removed to stay within a token budget, that information disappears unless the application explicitly preserves it somewhere else.</p><p>An LLM does not independently remember a previous API call. The application must provide that information again or connect the model to an external memory system.</p><p>This is why a large context window does not automatically provide long-term memory.</p><blockquote><em>A larger context window is a bigger workbench, not a filing cabinet.</em></blockquote><p>A bigger workbench lets the agent keep more material visible while it works. But when the workbench is cleared, the material still disappears unless something moves the important pieces into durable storage.</p><p>That was the first failure in my harness.</p><p>The successful fix was visible during session one, but nothing promoted the outcome beyond the active context.</p><p>However, preserving the entire conversation would not have fully solved the problem.</p><p>There was another distinction I had missed.</p><h3>Memory Is Not Authoritative State</h3><p><strong>In short:</strong> memory tells you what happened. It doesn’t guarantee what’s still true right now — for that, you check the system’s actual state.</p><p>Consider these two statements:</p><p>Memory: “BUG-142 was fixed during yesterday’s session.”</p><p>Application state: BUG-142.status = COMPLETED</p><p>They are related, but they are not the same.</p><p>The first is a historical record. It tells the agent that an event occurred.</p><p>The second represents the task tracker’s current source of truth.</p><p>Memory can tell the agent what happened previously, what was learned, or which approach worked.</p><blockquote><em>Memory tells the agent what happened. State tells the system what is true now.</em></blockquote><p>This distinction matters because memories can become stale, incomplete, or wrong.</p><p>Suppose the agent retrieves a memory saying: BUG-142 is open.</p><p>That memory may have been accurate when it was written. It does not prove that the bug is still open today.</p><p>Before acting, the agent should query the task tracker, inspect the repository, run the relevant tests, or reproduce the issue.</p><p>A retrieved memory is a claim from the past. It is not automatically proof of the present.</p><p>In the original incident, the system failed in two ways:</p><ol><li>It did not preserve a useful record of the completed fix.</li><li>It did not update the authoritative task state.</li></ol><p>With that distinction established, we can classify what the agent actually needed to remember.</p><h3>1. Working Memory: What Am I Doing Right Now?</h3><p><strong>In short:</strong> whatever the agent needs to finish the current task, and nothing more than that.</p><p>Working memory contains the information the agent needs to continue its current task.</p><p>For BUG-142, working memory might look like this:</p><p>Current task: Fix BUG-142 in the migration service Current hypothesis: The dependency table is initialized too late Current step: Run the integration test suite Latest observation: Three migration tests are failing Files being modified: migration_runner.py, dependency_loader.py</p><p>This information supports active execution.</p><p>It helps the agent answer questions such as:</p><ul><li>What is the current goal?</li><li>Which step am I performing?</li><li>What did the latest tool call return?</li><li>Which files have I changed?</li><li>What remains incomplete?</li></ul><p>Working memory often lives in the model’s context, an agent-state object, a workflow checkpoint, or a short-lived session store. It is temporary and task-specific rather than a durable record of everything the system has learned.</p><p>IBM similarly describes short-term memory as recent information used for immediate decision-making and conversational continuity. [</p><p>Working memory is slightly different from the other three categories.</p><p>Episodic, semantic, and procedural memories can survive across sessions. Working memory describes the agent’s active information, whether it is held directly in the context window or temporarily checkpointed outside it.</p><p>Its temporary nature is not necessarily a flaw.</p><p>After the task is complete, the agent probably does not need to preserve every intermediate hypothesis, partial code fragment, failed command, or abandoned line of reasoning.</p><p>The problem appears when an important outcome exists only in working memory.</p><p>In my case, this information disappeared:</p><p>Latest result: Integration tests passed Task outcome: BUG-142 fixed successfully</p><p>The harness treated a significant outcome as temporary execution context.</p><blockquote><em>Working memory supports active execution. It should not be the only record of completed work.</em></blockquote><h3>2. Episodic Memory: What Happened?</h3><p><strong>In short:</strong> a specific thing that happened, with enough detail to be useful later — not a raw transcript.</p><p>Episodic memory records specific experiences.</p><p>An episode is not merely a fact. It is something that happened in a particular situation, usually with a time, action, and outcome.</p><p>For BUG-142, a useful episodic memory might look like this:</p><p>Event: BUG-142 reproduced during migration initialization Context: The dependency table was unavailable when the service started Action: Changed the migration execution order Outcome: Integration tests passed Evidence: Commit a7f43d2 Time: 2026–09–08 14:20</p><p>This memory tells a future agent:</p><blockquote><em>We have encountered this situation before.</em></blockquote><p>It can help prevent repeated work, provide useful examples, and show which previous attempts succeeded or failed.</p><p>CoALA separates episodic memory from semantic memory because a record of experience serves a different purpose from generalized knowledge. Episodic memory captures experiences and interactions, while semantic memory represents facts and concepts that are not primarily tied to a particular event.</p><p>Episodic memory is also not the same as chat history.</p><p>A transcript might contain hundreds of messages, tool outputs, speculative ideas, corrections, and repeated information.</p><p>A useful episode is usually more structured:</p><p><strong>Event + Context + Action + Outcome + Time + Evidence</strong></p><p>Consider the difference:</p><p>Raw transcript: “We should probably inspect the initialization order…”</p><p>Useful episode: “Changing the dependency initialization order fixed BUG-142. Integration tests passed in commit a7f43d2.”</p><p>The second representation is easier to retrieve and much more useful during a future task.</p><p>Episodic memory can still fail.</p><p>The system may preserve the action but lose the outcome:</p><p>Attempted: Changed migration order</p><p>Without recording whether the attempt succeeded, a future agent may repeat the experiment unnecessarily.</p><p>The opposite can also happen. An agent may retrieve a successful episode from six months ago even though the architecture has since changed.</p><blockquote><em>Episodic memory preserves the past. It does not automatically describe the present.</em></blockquote><blockquote>That is why an episode should retain its time, context, evidence, and outcome.</blockquote><h3>3. Semantic Memory: What Do I Know?</h3><p><strong>In short:</strong> a fact worth keeping, independent of the one event that taught it to you.</p><p>An episode records what happened.</p><p>Semantic memory records what the system learned from it.</p><p>The BUG-142 episode might produce this reusable fact:</p><p>The migration service requires the dependency table to exist before initialization begins.</p><p>This knowledge is no longer primarily about one debugging session. It is a generalized fact about the system.</p><p>Other examples of semantic memory include:</p><ul><li>The service uses PostgreSQL</li><li>The API limit is 600 requests per minute</li><li>Customer identifiers must not appear in logs</li><li>The repository follows a service-repository pattern</li><li>The user prefers concise technical explanations</li><li>Migration scripts must remain backward compatible</li></ul><p>Semantic memory includes facts, concepts, constraints, relationships, and preferences. It is usually long-lived, but it must remain revisable because facts and preferences can change. [<a href="https://ibm.com/">ibm.com</a>], [<a href="https://mongodb.com/">mongodb.com</a>]</p><p>The difference between episodic and semantic memory is subtle but important:</p><p>Episodic: “BUG-142 occurred yesterday because the dependency table was unavailable during initialization.”</p><p>Semantic: “Migration initialization requires the dependency table to exist first.”</p><p>Episodic memory remembers the experience. Semantic memory remembers what the experience taught us.</p><p>Semantic memory has its own failure mode: stale knowledge.</p><p>Suppose the system later adopts a new initialization mechanism that no longer requires the dependency table first.</p><p>The original fact is no longer valid.</p><p>If the memory system simply appends the new fact without replacing or superseding the old one, the agent may retrieve both:</p><p>Memory A: Dependency table must exist before initialization.</p><p>Memory B: Initialization no longer depends on the dependency table.</p><p>Now the agent has memory, but not clarity.</p><p>A fact that was once correct can become more dangerous than no fact at all because the agent may act on it confidently.</p><p>Semantic memory therefore needs a correction path. The system must eventually answer:</p><ul><li>Who can update the fact?</li><li>Which source established it?</li><li>When was it last verified?</li><li>Does a newer version supersede it?</li><li>Should the old version be deleted or preserved historically?</li></ul><p>Those questions belong to memory engineering, which we will address in the next article.</p><p>For now, the important point is this:</p><blockquote><em>Semantic memory preserves reusable knowledge, not merely a record of an event.</em></blockquote><h3>4. Procedural Memory: How Should I Do It?</h3><p><strong>In short:</strong> not what’s true, but what to actually do about it.</p><p>Procedural memory tells the agent how to perform a task.</p><p>It represents skills, workflows, operational rules, and repeatable methods.</p><p>For the bug example, the system might derive this procedure:</p><p>Before running migration initialization: 1. Verify that the dependency table is available 2. Run the migration integration tests 3. Record the test result 4. Update the task tracker 5. Attach the commit reference 6. Verify that the issue no longer reproduces</p><p>That is not simply a fact.</p><p>The semantic fact is: The dependency table must exist before initialization.</p><p>The procedural rule is: Before initialization, verify dependency-table availability.</p><p>Semantic memory tells the agent what is true. Procedural memory tells the agent what to do.</p><p>Other examples include:</p><ul><li>How to roll back a failed deployment</li><li>How to investigate a payment failure</li><li>Which tests must run before closing a bug</li><li>How to review a pull request</li><li>When to request human approval</li><li>Which tool must be called before modifying production data</li></ul><p>Procedural memory can be represented through system instructions, versioned runbooks, skills, workflow definitions, executable code, or learned action patterns.</p><p>CoALA treats procedures as a distinct part of agent memory and connects them to both the model’s capabilities and the agent’s explicit code.</p><p>Procedural memory should generally be versioned more like software than accumulated like conversation history.</p><p>If an organization changes its deployment process, the agent should not retrieve five historical procedures and guess which one is current.</p><p>A production procedure needs:</p><ul><li>An owner</li><li>A version</li><li>An effective date</li><li>A clear scope</li><li>A replacement path</li><li>Evidence that it remains valid</li></ul><p>In my original harness, a missing procedure contributed directly to the failure.</p><p>The agent successfully fixed the code, but no rule required it to convert that success into updated application state.</p><p>The missing step was not: Remember the whole conversation.</p><p>It was: After tests pass, record the outcome and mark the task completed.</p><p>That is a procedural-memory problem.</p><h3>One Bug, Four Memories, One Source of Truth</h3><p>The easiest way to understand this taxonomy is to represent the same bug in five different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h__0uMQSaOaxjPB4" /></figure><p><strong>Working memory</strong> — “I am currently fixing BUG-142. The next step is to run the integration tests.” Purpose: continue the current execution.</p><p><strong>Episodic memory</strong> — “BUG-142 was fixed during session one. Changing the dependency order made the tests pass.” Purpose: preserve a previous experience.</p><p><strong>Semantic memory</strong> — “The migration service requires its dependency table before initialization.” Purpose: preserve reusable knowledge.</p><p><strong>Procedural memory</strong> — “Before initializing migrations, verify the dependency table and run integration tests.” Purpose: preserve a repeatable method.</p><p><strong>Authoritative state</strong> — BUG-142.status = COMPLETED, BUG-142.commit = a7f43d2, BUG-142.tests = PASSED. Purpose: represent what the application currently considers true.</p><p>These representations are related, but they are not interchangeable.</p><p>The episode does not replace the task record.</p><p>The task record does not preserve everything learned during the incident.</p><p>The semantic fact does not define the complete debugging procedure.</p><p>The procedure does not prove that a particular bug was fixed.</p><p>And working memory should not be expected to survive the session indefinitely.</p><blockquote><em>The system did not merely fail to remember one thing. It failed to convert completed work into the correct durable representations.</em></blockquote><h3>Each Memory Type Breaks Differently</h3><p>When all information is placed in one undifferentiated memory store, diagnosing failures becomes difficult.</p><p>A better approach is to identify which information job failed.</p><p><strong>Working-memory failure</strong> — Symptom: the agent loses its current plan after a reset. Likely cause: task-progress information existed only in the context window or local process.</p><p><strong>Episodic-memory failure</strong> — Symptom: the agent repeats an experiment or task completed in an earlier session. Likely cause: the previous event, action, or outcome was not preserved or retrieved.</p><p><strong>Semantic-memory failure</strong> — Symptom: the agent confidently applies an outdated fact. Likely cause: a fact changed, but the old representation was never superseded.</p><p><strong>Procedural-memory failure</strong> — Symptom: the agent completes the technical work but skips an important operational step. Likely cause: the workflow was missing, outdated, ambiguous, or unavailable during execution.</p><p><strong>Authoritative-state failure</strong> — Symptom: the agent acts on an incorrect task status. Likely cause: the application’s source-of-truth record was not updated or checked.</p><p>Different information jobs require different write permissions, retrieval rules, retention periods, correction paths, and evaluation methods.</p><p>A vector index may help retrieve several kinds of memory, but the index itself does not determine what type of memory the content represents. [<a href="https://agentfieldbook.org/">agentfieldbook.org</a>], [<a href="https://cellcog.ai/">cellcog.ai</a>]</p><p>This gives us a practical rule:</p><blockquote><em>Classify the information before choosing the storage technology.</em></blockquote><h3>A Practical Classification Checklist</h3><p>When deciding what kind of information an agent has encountered, ask the following questions.</p><p><strong>Is the information needed only for the current execution?</strong> Use working memory. Examples: current plan, latest tool result, temporary hypothesis, current step.</p><p><strong>Is it a specific event that occurred?</strong> Use episodic memory. Examples: a deployment failed yesterday, a previous repair attempt did not work, the user rejected a proposed design, a bug was fixed in a particular session.</p><p><strong>Is it reusable knowledge?</strong> Use semantic memory. Examples: project architecture, user preferences, domain constraints, service relationships, business definitions.</p><p><strong>Is it a workflow, rule, or skill?</strong> Use procedural memory. Examples: deployment procedure, testing checklist, tool-use policy, escalation workflow, code-review process.</p><p><strong>Does it represent the current source of truth?</strong> Use authoritative application state. Examples: ticket status, account balance, deployment state, current inventory, approval status.</p><p>Sometimes one experience should produce several representations.</p><p>A failed deployment might create:</p><ul><li>Episodic: “The deployment failed at 14:20.”</li><li>Semantic: “Service X requires schema version 17.”</li><li>Procedural: “Verify schema compatibility before deployment.”</li><li>Authoritative state: deployment.status = ROLLED_BACK</li></ul><p>That is not unnecessary duplication.</p><p>Each representation answers a different question.</p><h3>What the Harness Should Have Done</h3><p>The context did not need to live forever.</p><p>Instead, the harness needed to promote important outcomes before clearing the session.</p><p>The corrected flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RMa6kQh-vd-ZYhcy" /></figure><p>Now clearing the previous conversation is safe.</p><p>The raw transcript can disappear because the useful information has been converted into the forms that need to survive.</p><blockquote><em>Context should be allowed to disappear. Important outcomes should not disappear with it.</em></blockquote><h3>Classification Is Only the Beginning</h3><p>Once the information has been classified correctly, the harder engineering questions begin:</p><ul><li>What deserves to be stored?</li><li>Where should each memory type live?</li><li>Who is allowed to write it?</li><li>When should it be retrieved?</li><li>How should it enter the context window?</li><li>When should it be updated?</li><li>When should it expire?</li><li>What happens when two memories disagree?</li><li>How do we measure whether memory improved the agent?</li></ul><p>Those questions are part of memory engineering.</p><p>But implementation begins with classification.</p><p>Before choosing a vector database, memory framework, or retrieval strategy, ask:</p><blockquote><em>What kind of information is the agent trying to preserve?</em></blockquote><p>The goal is not to make an agent remember everything.</p><p>It is to make sure the right information survives, in the right form, for the right reason.</p><h3>Up Next</h3><p><strong>Part 2: Agent Memory Is a Lifecycle, Not a Database</strong></p><p>In Part 2, we will follow information through the complete memory loop:</p><p><strong>Experience → Extract → Decide → Store → Retrieve → Inject → Verify → Act → Update or Forget</strong></p><p>Because identifying a memory correctly is only the first step.</p><p>The system still has to make that memory useful.</p><p><strong>Have you seen an agent repeat completed work or confidently act on information that was already stale? Which kind of memory failed?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ff3582f4615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Model Isn’t the Problem. Your Harness Might Be.]]></title>
            <link>https://medium.com/@prashantx7979/your-model-isnt-the-problem-your-harness-might-be-78b16bb2fb06?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b16bb2fb06</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 11:42:03 GMT</pubDate>
            <atom:updated>2026-09-02T11:42:03.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E7FrbNv7coY9tFxg" /></figure><h3>Same Model, Same Weights, 13.7-Point Swing: What Actually Changed</h3><p>Three weeks ago, my agent tried to fix the same bug twice in one run.</p><p>Not because it couldn’t fix the code.</p><p>It had already fixed it five minutes earlier.</p><p>It just had no idea.</p><p>I spent a good ten minutes assuming the model had gotten dumber.</p><p>It hadn’t.</p><p>Nothing was wrong with the model. Nothing was wrong with my prompt either.</p><p>The problem was that <strong>my setup wasn’t keeping track of what the agent had already done.</strong></p><p>So as far as the model was concerned, this was the first time it had ever seen that bug.</p><p>That one dumb bug is basically the whole point of this post.</p><p>I started looking into how much of an agent’s performance actually comes from the model, and how much comes from everything wrapped around it.</p><p>The answer surprised me.</p><p>On the same model, with the same weights, changing the harness can create a <strong>13.7-point swing</strong> on Terminal-Bench 2.0.</p><p>So if the model didn’t change, what did?</p><p><strong>The harness.</strong></p><p>What the harness actually is</p><p>The simplest definition I’ve found is:</p><blockquote><strong><em>The harness is everything around the model that controls how the model interacts with the task.</em></strong></blockquote><p>The loop deciding what happens next.</p><p>The tools it can use.</p><p>What it remembers.</p><p>What context it sees.</p><p>What happens when a tool fails.</p><p>When it should stop.</p><p>How its work gets verified.</p><p>None of these things are the model itself.</p><p>But all of them decide whether the model’s reasoning turns into a finished task or a mess.</p><p>Here’s how I picture it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cs4AUa1U62C4-7HE" /></figure><p>The model is the brain.</p><p>The harness is everything that gives that brain the right information, tools and feedback to actually get the job done.</p><p>Once I started looking at agents this way, a lot of my <strong>“the model is bad at this”</strong> problems became:</p><p><strong>“My harness never gave the model a chance.”</strong></p><p>So let’s go through the problems one by one.</p><h3>Problem 1: The agent forgets what it already did</h3><p>This was my bug from three weeks ago.</p><p>Every time the model runs, the harness builds a new context from the system instructions, available tools and conversation history.</p><p>If that history isn’t carried forward properly, or important information gets pushed out, the model isn’t really “forgetting” in the human sense.</p><p><strong>It was simply never told.</strong></p><p>One common solution is to summarize history as the run gets longer instead of continuously dumping everything back into the context.</p><p>Keep the decisions that matter.</p><p>Keep what’s still broken.</p><p>Throw away the noise.</p><p>Give the model a short, useful state instead of a growing wall of text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v1eIE0hTDavZogpq" /></figure><p>That’s memory as an engineering problem, not a model problem.</p><h3>Problem 2: One failed tool call kills the run</h3><p>A tool throws an error.</p><p>The code crashes.</p><p>The agent stops.</p><p>That’s the difference between an agent that can recover and one that’s dead the moment an API or tool call goes wrong.</p><p>The fix is actually pretty simple.</p><p><strong>Don’t hide the failure. Turn it into an observation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*InLR_Jpy3pfuNQBy" /></figure><p>It’s basically the same as telling a junior engineer:</p><blockquote><em>“That failed because the file doesn’t exist.”</em></blockquote><p>You don’t fire them because the first attempt failed.</p><p>You give them the information they need to try again.</p><p>A good harness does the same thing.</p><h3>Problem 3: More context can actually make the model worse</h3><p>This one surprised me.</p><p>You’d think a bigger context window is always better.</p><p>It isn’t.</p><p>As you keep adding more information, the model has more things to pay attention to.</p><p>Important information can get buried.</p><p>Old tool outputs stay around.</p><p>Irrelevant conversations accumulate.</p><p>And eventually you’re spending tokens giving the model information that it doesn’t actually need for the current step.</p><p>So a good harness shouldn’t ask:</p><p><strong>“What can I fit into the context?”</strong></p><p>It should ask:</p><p><strong>“What does the model actually need right now?”</strong></p><p>Instead of pasting an entire codebase, fetch the relevant function.</p><p>Instead of sending the entire history, keep the decisions that matter.</p><p>Instead of keeping every tool output, preserve the useful observations.</p><p>Think of it more like:</p><p>Need one function? → retrieve one function. Need previous decision? → retrieve that decision. Need current task state? → retrieve current state.</p><p>Not:</p><p>Here is everything we’ve ever seen. Good luck.</p><h3>Problem 4: The agent doesn’t know when to stop</h3><p>Put a model inside a loop without proper termination rules and you’ll eventually see one of two things.</p><p>It stops too early.</p><p>Or it keeps going after the task is already finished.</p><p>Neither necessarily means the model is bad.</p><p>It can simply mean the <strong>orchestration loop has no clear definition of done.</strong></p><p>Under the hood, the agent loop is still basically a loop:</p><p>while not finished: ask model execute tool observe result</p><p>The important question is:</p><p><strong>What makes finished true?</strong></p><p>A good harness can define explicit stopping conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*993fmoBG6BFoR0jX" /></figure><ul><li>task completed</li><li>verification passed</li><li>no useful tool action remains</li><li>maximum turns reached</li><li>budget exhausted</li><li>failure threshold reached</li></ul><p>“Keep going until it feels done” isn’t a real termination strategy.</p><p>It’s the absence of one.</p><h3>Problem 5: The agent says “done” and it isn’t</h3><p>This is probably the most important one.</p><p>An agent can say:</p><blockquote><em>“The bug is fixed.”</em></blockquote><p>That doesn’t mean the bug is fixed.</p><p>An agent can say:</p><blockquote><em>“All tests pass.”</em></blockquote><p>That doesn’t mean the tests pass.</p><p>If the same model writes the code and then decides whether the code is correct, you’re effectively asking it to grade its own homework.</p><p>The better approach is to separate <strong>doing</strong> from <strong>verifying</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*QJ7ulqZffiHhF1Lz" /></figure><p>“Done” should be a <strong>claim that needs verification</strong>, not a fact you automatically trust.</p><h3>This isn’t just a nice theory</h3><p>The interesting part is that these aren’t just architectural opinions.</p><p>Harness design can produce significant differences in benchmark performance even when the underlying model stays the same.</p><p>On Terminal-Bench 2.0, different harnesses have produced substantially different results with the same underlying model. The numbers can move from roughly the low-60s to the mid-70s depending on the harness.</p><p>That’s a huge difference for something that isn’t a model upgrade.</p><p>And we’ve also seen cases where reducing the number of tools available to an agent improved both its success rate and speed.</p><p>That tells me something important:</p><p><strong>More tools ≠ better agent.</strong></p><p><strong>More context ≠ better agent.</strong></p><p><strong>Bigger model ≠ automatically better system.</strong></p><p>The surrounding engineering matters.</p><p>One honest caveat, though.</p><p>You’ll sometimes see people say:</p><blockquote><strong><em>“The harness is 70% of agent performance.”</em></strong></blockquote><p>I’ve looked for a solid study behind that exact number and couldn’t find one.</p><p>So I wouldn’t repeat it as a fact.</p><p>The stronger argument is simply the one we can actually observe:</p><p><strong>Hold the model constant. Change the harness. Performance changes.</strong></p><p>That’s enough to make the point.</p><h3>Where I’d push back on my own argument</h3><p>It would be dishonest to say the harness always matters more than the model.</p><p>It doesn’t.</p><p>Sometimes the model is genuinely the bottleneck.</p><p>And as models improve, some problems that previously required complicated scaffolding can disappear.</p><p>That’s actually an important point.</p><p>A harness is <strong>scaffolding</strong>.</p><p>If a newer model becomes better at something, the workaround you built around the old model may no longer be necessary.</p><p>So this isn’t:</p><blockquote><em>“Build the biggest possible harness.”</em></blockquote><p>It’s:</p><blockquote><strong><em>“Build the minimum harness that reliably gets the job done.”</em></strong></blockquote><p>And keep reevaluating it as the models improve.</p><p>Good scaffolding gets removed when the building becomes strong enough to stand without it.</p><h3>What actually changed for me</h3><p>Before I reach for a bigger model now, I check the harness first.</p><p>Can the agent remember what it already did?</p><p>Can it recover from tool failures?</p><p>Am I giving it too much context?</p><p>Does it have a proper stopping condition?</p><p>Is the result actually being verified?</p><p>Because sometimes the problem isn’t:</p><p><strong>“We need a smarter model.”</strong></p><p>It’s:</p><p><strong>“We need a better system around the model.”</strong></p><p>The model is only one part of an agent.</p><p>The rest of the system decides how often that intelligence gets wasted.</p><p>That’s what I’m going to explore in this series:</p><p><strong>Memory → Tools → Context → Loops → Verification</strong></p><p>Not just what they are, but how they actually change an agent in production.</p><p><strong>Have you ever fixed an agent by changing the harness instead of the model? What actually moved the needle for you?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b16bb2fb06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG From First Principles]]></title>
            <link>https://medium.com/@prashantx7979/rag-from-first-principles-5cabc01f9a63?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cabc01f9a63</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 14:08:11 GMT</pubDate>
            <atom:updated>2026-08-29T14:08:11.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ShgLIMYF6nEl1Pi1" /></figure><p>A RAG system doesn’t understand your documents. <strong>It measures how close your question sits to them, in a space made entirely of numbers.</strong> Here’s what actually happens between the question and the answer — worked by hand first, then in the architecture that runs it at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*ot3ztpeke2DVS9O8" /></figure><p><strong>Plain terms</strong> : Ask an AI system something it was never trained on — your company’s internal docs, last week’s news, your own notes — and it has two options: guess, or go look it up first. Retrieval-Augmented Generation (RAG) is the “go look it up first” option. Underneath, it’s mostly arithmetic: turn meaning into numbers, then find which numbers sit closest together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2l9ZRJLge2bcBmkQ" /></figure><h3>Turning meaning into numbers</h3><p><strong>Plain terms:</strong> Computers can’t compare “meaning” directly, so every sentence gets converted into a list of numbers — a vector — by a model trained to place similar meanings near each other in that numeric space. Two sentences about cooking end up close together. A sentence about cooking and a sentence about the stock market end up far apart.</p><p><strong>Under the hood:</strong> In production, that vector usually has hundreds or thousands of dimensions, produced by a neural network trained on huge volumes of text. Nobody hand-designs these numbers — the model learns them. But the comparison step — measuring how close two vectors sit — is genuinely hand-computable. Here it is, with numbers small enough to check yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tj5iD1veJzDdv6ey" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*jKLP2bVmemBIWmPG" /></figure><p>Note</p><p>In practice, vectors are normalized to length 1 before comparison, which makes the dot product equivalent to cosine similarity — the angle between vectors, independent of their length. The mechanics above are identical either way.</p><h3>Why you can’t check every document</h3><p><strong>Plain terms :</strong> The by-hand method above works great for 3 documents. It falls apart at 10 million. Comparing a query against every single vector one at a time — a “flat” or brute-force search — is perfectly accurate, but too slow once the dataset is large.</p><p><strong>Under the hood :</strong> Vector databases solve this with <strong>Approximate Nearest Neighbor</strong> (ANN) search. The dominant algorithm, <strong>HNSW</strong> (Hierarchical Navigable Small World), builds a multi-layer graph over the vectors. The top layer has very few nodes with long-range connections — a highway system, good for covering distance fast. Each layer below has more nodes with shorter connections — local streets. A search starts on the highway layer, jumps toward the right neighborhood quickly, then descends layer by layer, narrowing in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CXw1IBJYX8Cb4R2i" /></figure><p>Enter at the sparse top layer, descend toward the match — never touching most of the bottom layer at al</p><h3>Getting documents ready to search</h3><p><strong>Plain terms:</strong> You don’t feed a whole 50-page PDF in at once — models have a hard limit on how much text they can read in one go (the context window), and searching a whole document is far less useful than finding the one paragraph with the actual answer. So documents get split into smaller pieces first.</p><p><strong>Under the hood:</strong> <strong>Fixed-size chunking</strong> splits every N characters — cheap, but it can cut a sentence in half and destroy its meaning. <strong>Semantic chunking</strong> splits on natural boundaries instead — paragraphs, sections, topic shifts — so each chunk stays one complete idea. Either way, chunks usually overlap slightly, so an idea sitting on a boundary doesn’t get orphaned in neither chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QX70CrltfDvIxGEj" /></figure><h3>Finding the right chunks</h3><p><strong>Plain terms:</strong> When someone asks a question, the system turns it into a vector the same way it did for every document, then searches for the closest matches. But vector search alone has a blind spot: it’s good at “meaning,” bad at exact terms — a specific error code, a SKU, an acronym — because those don’t carry much semantic weight in vector space.</p><p><strong>Under the hood:</strong> <strong>Hybrid search</strong> runs a vector search and a traditional keyword search (typically BM25) in parallel, then fuses the two ranked lists — commonly with <strong>Reciprocal Rank Fusion (RRF)</strong>, which rewards documents that rank well in either list without requiring the two systems to agree on a shared score scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NDBwPHTo5QMr-wtC" /></figure><p>Two blind spots covering each other, then one slow-but-precise pass to fix the ordering.</p><p>Even after fusion, the order isn’t perfect, because vector search compares query and document independently (a “bi-encoder”) for speed. <strong>Reranking</strong> fixes this: take the top ~50 candidates, run them through a slower cross-encoder that looks at the query and each document together, and re-sort based on that closer comparison. A bit of latency, traded for meaningfully better ordering.</p><h3>Turning retrieval into an answer</h3><p><strong>Plain terms:</strong> Once the system has the right chunks, it hands them to the language model with the original question and one instruction: answer using only this information.</p><p><strong>Under the hood :</strong> The prompt is typically structured as a system instruction, the retrieved context, then the user’s question. The context window limit applies here too — retrieve too much, or chunk too generously, and you either blow the limit or crowd out the model’s ability to reason over what’s there.</p><p>Explicitly instructing the model to say “I don’t know” when the context lacks the answer meaningfully reduces hallucination, though it doesn’t eliminate it — a model can still misread correct context or blend it with something from training. This is why production systems pair generation with an evaluation layer, not just a well-worded prompt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cabc01f9a63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forward Deployed Engineer is the new buzzword.]]></title>
            <link>https://medium.com/@prashantx7979/forward-deployed-engineer-is-the-new-buzzword-7a7547719839?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a7547719839</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 07:36:29 GMT</pubDate>
            <atom:updated>2026-06-20T07:36:29.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forward Deployed Engineer is the new buzzword. I think service companies have been doing this for years — just without the name.</h3><p>If you’ve been on tech Twitter or LinkedIn in the last year, you’ve seen the term <strong>FDE — Forward Deployed Engineer</strong> — everywhere. Palantir made it famous. Now every AI startup wants one. The pitch is simple: instead of sitting in your own office building a generic product, you go and sit <em>inside</em> the client’s environment, understand their actual mess, and build something that solves their actual problem.</p><p>It’s being sold as a new role. A new way of working that only fast AI startups do.</p><p>I work as an AI Engineer at HCLTech — a service-based company. And the more I read about FDE, the more I realized: this is not new for us. We’ve been doing a version of this for years. We just never called it that, and most people outside the industry don’t know what this work actually looks like now that AI agents are part of it.</p><p>Let me explain with a real kind of project I work on.</p><p><strong>The setup</strong></p><p>Say we have a client — a banking company. They have years of legacy infrastructure: old applications, databases, manual processes, and now they want to move all of it to the cloud — AWS, Azure, sometimes both. This is not a small migration. Banking environments have compliance rules, sensitive customer data, and zero tolerance for downtime or data leaks.</p><p>The old way this kind of migration happens: a team of engineers goes in, manually documents every system, manually maps dependencies, manually writes the architecture diagrams, manually writes the infrastructure code. This easily takes <strong>4 to 6 months</strong> for a mid-sized environment, sometimes longer.</p><p><strong>What we’re doing differently now</strong></p><p>We go into the client’s own environment — not remote, not outside, <em>inside</em> their cloud and infra setup, with their permissions and their security boundaries. And instead of doing each step by hand, we run a chain of AI agents that do the heavy lifting:</p><ul><li>An agent that goes through all their resources and <strong>segregates and classifies the data</strong> — what’s an application, what’s a database, what’s just storage, what’s redundant.</li><li>An agent that <strong>refines and cleans</strong> this raw inventory into something usable.</li><li>A <strong>migration planning agent</strong> that looks at everything and proposes a sequencing and strategy — what should move first, what depends on what.</li><li>An agent that generates the <strong>As-Is document</strong> — a full picture of their current architecture, exactly as it exists today.</li><li>Another agent that generates the <strong>To-Be document</strong> — what the architecture should look like after migration to the cloud.</li><li>An agent that <strong>validates the environment</strong> — checking that what’s documented actually matches reality.</li><li>An agent that auto-generates the <strong>architecture diagrams</strong> from all of this — so nobody is manually dragging boxes in a diagramming tool.</li><li>An agent that <strong>scans the databases</strong> for structure, dependencies, and risk.</li><li>Agents that assist with the actual <strong>provisioning</strong> to the cloud.</li><li>A <strong>drift agent</strong> that continuously checks the difference between what was planned and what actually exists — catching configuration drift before it becomes a security or compliance issue.</li><li>And finally, an agent that generates the <strong>Terraform code</strong> needed to provision and manage the new infrastructure.</li></ul><p>All of this runs <em>inside</em> the client’s own environment. Their data never has to leave their boundary for us to do this work. That one design decision does two things at once: it keeps the security posture exactly where the client wants it, and it builds trust — because they can see, audit, and control everything happening on their own ground.</p><p><strong>The result</strong></p><p>What used to take 6 months is now realistically getting done in about a month. Not because we’re cutting corners, but because the slow, repetitive, document-heavy parts of migration — the parts that ate up most of the timeline — are now handled by agents working continuously, instead of engineers working sequentially.</p><p><strong>Why I’m writing this</strong></p><p>I keep seeing FDE described as something only product startups do. I don’t think that’s accurate anymore. The core idea of FDE — go to where the client’s actual problem lives, work inside their constraints, build something that fits their specific reality instead of a generic product — is exactly what’s happening in large service companies doing AI-driven transformation work right now. We’re just not calling it that on our business cards.</p><p>Maybe the title doesn’t matter. What matters is the shift: engineers who used to write code in isolation are now expected to understand a client’s entire environment, security model, and business context — and then build agents and systems that operate safely inside it. That’s the real skill the market is pricing in right now, whatever you choose to call it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a7547719839" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Ready AI Agents with LangChain and LangGraph]]></title>
            <link>https://medium.com/@prashantx7979/building-production-ready-ai-agents-with-langchain-and-langgraph-13715a9a00e4?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/13715a9a00e4</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 12:01:16 GMT</pubDate>
            <atom:updated>2026-04-24T12:01:16.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Zero to a Robust, Scalable Agent System — A Practical Guide</h3><blockquote>You’ve played with ChatGPT. You’ve called the OpenAI API. Maybe you’ve even chained a few prompts together. But the moment you try to build something real — something that remembers context, handles errors gracefully, protects user data, and doesn’t drain your API budget — you realize how big the gap is between “it works on my laptop” and “it’s ready for production.”</blockquote><blockquote>This article closes that gap.</blockquote><h3>Table of Contents</h3><ol><li>What Is an AI Agent — Really?</li><li>Core Architecture: Messages, Tools, and Memory</li><li>Persistent Memory with SQLite</li><li>Streaming: Real-Time Responses in Agents</li><li>Middleware: The Unsung Hero of Production Systems</li><li>PII Protection: Keeping Sensitive Data Safe</li><li>Structured Outputs with Pydantic</li><li>Common Mistakes and How to Debug Them</li><li>Best Practices for Production</li><li>Conclusion</li></ol><h3>1. What Is an AI Agent — Really?</h3><p>Most people start their AI journey with a simple API call:</p><pre>response = openai.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What is 2 + 2?&quot;}]<br>)<br>print(response.choices[0].message.content)</pre><p>This works. But it’s not an agent. It’s a one-shot query — no memory, no tools, no decision-making loop.</p><p>An <strong>AI agent</strong> is different. It is an autonomous system that:</p><ul><li>Maintains <strong>context</strong> across multiple turns of conversation</li><li>Can <strong>call tools</strong> (APIs, databases, web search, calculators) to gather information</li><li><strong>Decides</strong> what action to take next based on its current state</li><li><strong>Loops</strong> until it completes a goal, rather than stopping after one response</li></ul><p>Think of a human assistant. When you ask them to “research competitors and send a summary email,” they don’t do it in one step. They search the web, open links, take notes, synthesize information, draft the email, and send it — all in a loop, making decisions along the way. That’s what an agent does.</p><h3>Why LangChain and LangGraph?</h3><p><strong>LangChain</strong> is a framework that provides abstractions for working with LLMs: chat models, tools, prompt templates, output parsers, and memory. It handles the plumbing so you focus on logic.</p><p><strong>LangGraph</strong> builds on LangChain to give you a graph-based execution model. Instead of a linear chain, you define nodes (steps) and edges (transitions) — including conditional edges, loops, and parallel execution. This is what makes agents truly powerful.</p><p>Together, they give you:</p><ul><li>A standard way to pass messages between humans and AI</li><li>Built-in tool calling and tool result handling</li><li>Stateful execution with checkpointing</li><li>Composable middleware for production concerns</li></ul><p>Let’s build this, layer by layer.</p><h3>2. Core Architecture: Messages, Tools, and Memory</h3><p>Every agent interaction in LangChain revolves around <strong>messages</strong>. This is the fundamental contract between the human and the AI.</p><h3>The Message Types</h3><pre>from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, ToolMessage</pre><pre># A message from the user<br>user_msg = HumanMessage(content=&quot;What&#39;s the weather in Mumbai?&quot;)</pre><pre># A message from the AI (may include tool calls)<br>ai_msg = AIMessage(content=&quot;Let me check that for you.&quot;)</pre><pre># System-level instructions (sets agent behavior)<br>sys_msg = SystemMessage(content=&quot;You are a helpful weather assistant.&quot;)</pre><pre># Result of a tool execution<br>tool_msg = ToolMessage(content=&#39;{&quot;temp&quot;: 32, &quot;humidity&quot;: 85}&#39;, tool_call_id=&quot;abc123&quot;)</pre><p><strong>Why this matters:</strong> A common beginner mistake is passing a raw string where a HumanMessage is expected. LangGraph&#39;s agent nodes expect structured message objects — not strings. Mixing these up causes confusing errors that look like type mismatches.</p><h3>Tools: Extending the Agent’s Reach</h3><p>Tools are Python functions decorated with @tool. The agent decides when to call them and with what arguments.</p><pre>from langchain_core.tools import tool</pre><pre>@tool<br>def get_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Fetch current weather for a given city.&quot;&quot;&quot;<br>    # In production, this would call a real weather API<br>    weather_data = {<br>        &quot;Mumbai&quot;: &quot;32°C, Humid, Partly Cloudy&quot;,<br>        &quot;Delhi&quot;: &quot;28°C, Clear, Low Humidity&quot;,<br>    }<br>    return weather_data.get(city, f&quot;No data available for {city}&quot;)</pre><pre>@tool<br>def calculate_bmi(weight_kg: float, height_m: float) -&gt; str:<br>    &quot;&quot;&quot;Calculate BMI given weight in kg and height in meters.&quot;&quot;&quot;<br>    bmi = weight_kg / (height_m ** 2)<br>    category = (<br>        &quot;Underweight&quot; if bmi &lt; 18.5 else<br>        &quot;Normal&quot; if bmi &lt; 25 else<br>        &quot;Overweight&quot; if bmi &lt; 30 else<br>        &quot;Obese&quot;<br>    )<br>    return f&quot;BMI: {bmi:.1f} — {category}&quot;</pre><h3>Building a Basic Agent with LangGraph</h3><p>Here’s the minimal skeleton of a LangGraph agent:</p><pre>from langgraph.prebuilt import create_react_agent<br>from langchain_openai import ChatOpenAI</pre><pre># Initialize the LLM<br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)</pre><pre># Bundle tools<br>tools = [get_weather, calculate_bmi]</pre><pre># Create the agent<br>agent = create_react_agent(<br>    model=llm,<br>    tools=tools,<br>    state_modifier=&quot;You are a helpful assistant with access to weather and health tools.&quot;<br>)</pre><pre># Run the agent<br>result = agent.invoke({<br>    &quot;messages&quot;: [HumanMessage(content=&quot;What&#39;s the weather in Mumbai today?&quot;)]<br>})</pre><pre>print(result[&quot;messages&quot;][-1].content)</pre><p>Under the hood, LangGraph is running a <strong>ReAct loop</strong>: Reason → Act → Observe → Repeat. The agent sees the user’s message, reasons about what tool to use, calls the tool, reads the result, and decides whether to respond or loop again.</p><h3>3. Persistent Memory with SQLite</h3><p>One of the biggest jumps from toy agent to real agent is <strong>memory</strong>. Without memory, every conversation starts from scratch — your agent forgets everything the moment the function returns.</p><p>LangGraph solves this with <strong>checkpointers</strong>. A checkpointer saves the agent’s full state (all messages, tool call history, intermediate steps) to a persistent store after each step. SqliteSaver uses a local SQLite database — perfect for development and lightweight production use.</p><h3>Setting Up SqliteSaver</h3><pre>from langgraph.checkpoint.sqlite import SqliteSaver<br>import sqlite3</pre><pre># Create a persistent SQLite connection<br>conn = sqlite3.connect(&quot;agent_memory.db&quot;, check_same_thread=False)<br>checkpointer = SqliteSaver(conn)</pre><pre># Inject the checkpointer into the agent<br>agent = create_react_agent(<br>    model=llm,<br>    tools=tools,<br>    checkpointer=checkpointer,<br>    state_modifier=&quot;You are a helpful assistant.&quot;<br>)</pre><h3>The thread_id: Your Agent’s Identity</h3><p>Every conversation in LangGraph is identified by a <strong>thread_id</strong>. This is how the agent knows whose history to load. Think of it as a session ID — the same thread_id connects all turns of the same conversation.</p><pre># Turn 1: User introduces themselves<br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;user_prashant_001&quot;}}</pre><pre>result = agent.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=&quot;Hi! My name is Prashant.&quot;)]},<br>    config=config<br>)<br>print(result[&quot;messages&quot;][-1].content)<br># → &quot;Hello Prashant! How can I help you today?&quot;</pre><pre># Turn 2: Later — same thread_id, agent remembers<br>result = agent.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=&quot;What&#39;s my name?&quot;)]},<br>    config=config<br>)<br>print(result[&quot;messages&quot;][-1].content)<br># → &quot;Your name is Prashant, as you mentioned earlier!&quot;</pre><p><strong>Why this matters in production:</strong> Without a thread_id, every invocation is stateless. With the wrong thread_id, you might accidentally load someone else’s conversation history. Always treat thread_id as a first-class piece of your application’s session management — generate it when a user session starts, and store it securely.</p><h3>What Gets Saved?</h3><p>The checkpointer saves the entire messages list — all HumanMessages, AIMessages, ToolMessages — as a snapshot at each node transition. When you resume a thread, LangGraph replays this state, and the agent sees the full conversation history just as if it never stopped.</p><h3>4. Streaming: Real-Time Responses in Agents</h3><p>Nobody likes staring at a blank screen waiting for a response. Streaming lets you show the agent’s output — token by token or step by step — as it’s being generated. This dramatically improves user experience.</p><p>LangGraph supports three streaming modes, each suited to different use cases.</p><h3>Mode 1: messages — Stream Tokens in Real Time</h3><p>Best for: Chat interfaces where you want that typewriter effect.</p><pre>async def stream_chat(user_input: str, thread_id: str):<br>    config = {&quot;configurable&quot;: {&quot;thread_id&quot;: thread_id}}<br>    <br>    async for chunk, metadata in agent.astream(<br>        {&quot;messages&quot;: [HumanMessage(content=user_input)]},<br>        config=config,<br>        stream_mode=&quot;messages&quot;<br>    ):<br>        # chunk is a message fragment (a few tokens at a time)<br>        if hasattr(chunk, &quot;content&quot;) and chunk.content:<br>            print(chunk.content, end=&quot;&quot;, flush=True)<br>    print()  # newline at end</pre><h3>Mode 2: updates — Stream Node-Level Changes</h3><p>Best for: Showing the agent’s “thinking” steps — which tool it called, what result came back.</p><pre>async def stream_with_steps(user_input: str, thread_id: str):<br>    config = {&quot;configurable&quot;: {&quot;thread_id&quot;: thread_id}}<br>    <br>    async for update in agent.astream(<br>        {&quot;messages&quot;: [HumanMessage(content=user_input)]},<br>        config=config,<br>        stream_mode=&quot;updates&quot;<br>    ):<br>        # update is a dict: {node_name: state_changes}<br>        for node_name, state_changes in update.items():<br>            print(f&quot;\n[Node: {node_name}]&quot;)<br>            for msg in state_changes.get(&quot;messages&quot;, []):<br>                if hasattr(msg, &quot;tool_calls&quot;) and msg.tool_calls:<br>                    for tc in msg.tool_calls:<br>                        print(f&quot;  🔧 Calling tool: {tc[&#39;name&#39;]} with {tc[&#39;args&#39;]}&quot;)<br>                elif hasattr(msg, &quot;content&quot;):<br>                    print(f&quot;  💬 {msg.content[:100]}...&quot;)</pre><h3>Mode 3: values — Stream Complete State Snapshots</h3><p>Best for: Debugging, logging, or when you need the full picture at each step.</p><pre>async def stream_full_state(user_input: str, thread_id: str):<br>    config = {&quot;configurable&quot;: {&quot;thread_id&quot;: thread_id}}<br>    <br>    async for state in agent.astream(<br>        {&quot;messages&quot;: [HumanMessage(content=user_input)]},<br>        config=config,<br>        stream_mode=&quot;values&quot;<br>    ):<br>        # state contains the entire messages list at this point<br>        last_msg = state[&quot;messages&quot;][-1]<br>        print(f&quot;State has {len(state[&#39;messages&#39;])} messages. Last: {type(last_msg).__name__}&quot;)</pre><h3>Choosing the Right Mode</h3><p>Mode What You Get When to Use messages Token-by-token chunks Chat UIs, real-time display updates Node-level diffs Progress indicators, step display values Full state at each step Debugging, audit logs</p><h3>5. Middleware: The Unsung Hero of Production Systems</h3><p>Here’s a truth most tutorials skip: the LLM call itself is the easy part. The hard part is everything around it — cost control, reliability, context management, and safety. That’s where <strong>middleware</strong> comes in.</p><p>In LangGraph, middleware wraps your agent’s execution, intercepting each step to apply cross-cutting concerns — just like middleware in a web framework (Express, Django, FastAPI).</p><h3>SummarizationMiddleware: Taming the Token Explosion</h3><p>Every message added to the conversation grows your context window. After 20 turns, you might be sending 10,000 tokens per request without realizing it. Costs spiral. Performance degrades. Eventually, you hit the context limit and crash.</p><p>SummarizationMiddleware solves this by periodically summarizing older messages into a compact summary, replacing the verbose history with a concise one.</p><pre>from langgraph.prebuilt.chat_agent_executor import AgentState<br>from langchain_core.messages import RemoveMessage</pre><pre>class SummarizationMiddleware:<br>    def __init__(self, llm, max_messages: int = 10, summary_prompt: str = None):<br>        self.llm = llm<br>        self.max_messages = max_messages<br>        self.summary_prompt = summary_prompt or (<br>            &quot;Summarize the following conversation in 3-5 bullet points, &quot;<br>            &quot;preserving all important facts, decisions, and user preferences:\n\n{history}&quot;<br>        )<br>    <br>    def __call__(self, state: AgentState) -&gt; AgentState:<br>        messages = state[&quot;messages&quot;]<br>        <br>        if len(messages) &lt;= self.max_messages:<br>            return state  # Nothing to summarize yet<br>        <br>        # Separate messages to summarize vs. keep recent ones<br>        to_summarize = messages[:-self.max_messages // 2]<br>        recent = messages[-self.max_messages // 2:]<br>        <br>        # Build the history text<br>        history_text = &quot;\n&quot;.join([<br>            f&quot;{type(m).__name__}: {m.content}&quot;<br>            for m in to_summarize<br>            if hasattr(m, &quot;content&quot;) and m.content<br>        ])<br>        <br>        # Generate summary<br>        summary_response = self.llm.invoke(<br>            self.summary_prompt.format(history=history_text)<br>        )<br>        <br>        # Replace old messages with summary<br>        summary_message = SystemMessage(<br>            content=f&quot;[Conversation Summary]\n{summary_response.content}&quot;<br>        )<br>        <br>        return {**state, &quot;messages&quot;: [summary_message] + recent}</pre><p><strong>Real-world impact:</strong> A 50-turn conversation might consume 25,000 tokens per request without summarization. With summarization triggering every 10 messages, you keep context under 3,000 tokens — a 90% cost reduction.</p><h3>ModelCallLimitMiddleware: Budget Control</h3><p>In production, a runaway agent can make hundreds of LLM calls in minutes. Maybe it’s stuck in a loop. Maybe a user is abusing the system. Either way, you need a circuit breaker.</p><pre>class ModelCallLimitMiddleware:<br>    def __init__(self, max_calls_per_session: int = 20):<br>        self.max_calls = max_calls_per_session<br>        self._call_counts: dict[str, int] = {}<br>    <br>    def __call__(self, state: AgentState, config: dict) -&gt; AgentState:<br>        thread_id = config.get(&quot;configurable&quot;, {}).get(&quot;thread_id&quot;, &quot;default&quot;)<br>        <br>        # Increment and check<br>        self._call_counts[thread_id] = self._call_counts.get(thread_id, 0) + 1<br>        <br>        if self._call_counts[thread_id] &gt; self.max_calls:<br>            raise RuntimeError(<br>                f&quot;Session &#39;{thread_id}&#39; exceeded the model call limit of {self.max_calls}. &quot;<br>                &quot;Please start a new conversation.&quot;<br>            )<br>        <br>        return state<br>    <br>    def reset(self, thread_id: str):<br>        &quot;&quot;&quot;Call this when a session legitimately ends.&quot;&quot;&quot;<br>        self._call_counts.pop(thread_id, None)</pre><h3>ToolCallLimitMiddleware: Preventing Tool Abuse</h3><p>Some tools are expensive (third-party APIs with per-call pricing) or dangerous if over-used (sending emails, making payments). Limit them per session.</p><pre>class ToolCallLimitMiddleware:<br>    def __init__(self, limits: dict[str, int]):<br>        &quot;&quot;&quot;<br>        limits: {&quot;send_email&quot;: 5, &quot;run_sql_query&quot;: 10, &quot;web_search&quot;: 20}<br>        &quot;&quot;&quot;<br>        self.limits = limits<br>        self._tool_counts: dict[str, dict[str, int]] = {}<br>    <br>    def __call__(self, state: AgentState, config: dict) -&gt; AgentState:<br>        thread_id = config.get(&quot;configurable&quot;, {}).get(&quot;thread_id&quot;, &quot;default&quot;)<br>        <br>        if thread_id not in self._tool_counts:<br>            self._tool_counts[thread_id] = {}<br>        <br>        # Check the most recent AI message for tool calls<br>        messages = state.get(&quot;messages&quot;, [])<br>        last_ai_msg = next(<br>            (m for m in reversed(messages) if isinstance(m, AIMessage)), None<br>        )<br>        <br>        if last_ai_msg and hasattr(last_ai_msg, &quot;tool_calls&quot;):<br>            for tool_call in last_ai_msg.tool_calls:<br>                tool_name = tool_call[&quot;name&quot;]<br>                limit = self.limits.get(tool_name)<br>                <br>                if limit is not None:<br>                    count = self._tool_counts[thread_id].get(tool_name, 0) + 1<br>                    self._tool_counts[thread_id][tool_name] = count<br>                    <br>                    if count &gt; limit:<br>                        raise RuntimeError(<br>                            f&quot;Tool &#39;{tool_name}&#39; has been called {count} times this session, &quot;<br>                            f&quot;exceeding the limit of {limit}.&quot;<br>                        )<br>        <br>        return state</pre><h3>ModelFallbackMiddleware: Reliability Under Failure</h3><p>Your primary model (GPT-4o, Claude Opus) will occasionally fail — rate limits, outages, timeouts. Don’t let your agent crash. Fall back gracefully.</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_anthropic import ChatAnthropic<br>import time</pre><pre>class ModelFallbackMiddleware:<br>    def __init__(self, primary_model, fallback_models: list, max_retries: int = 2):<br>        self.primary = primary_model<br>        self.fallbacks = fallback_models<br>        self.max_retries = max_retries<br>    <br>    def invoke_with_fallback(self, messages: list) -&gt; AIMessage:<br>        models = [self.primary] + self.fallbacks<br>        last_error = None<br>        <br>        for i, model in enumerate(models):<br>            for attempt in range(self.max_retries):<br>                try:<br>                    response = model.invoke(messages)<br>                    if i &gt; 0:<br>                        print(f&quot;⚠️  Used fallback model {i}: {type(model).__name__}&quot;)<br>                    return response<br>                except Exception as e:<br>                    last_error = e<br>                    print(f&quot;Model {type(model).__name__} failed (attempt {attempt+1}): {e}&quot;)<br>                    time.sleep(2 ** attempt)  # Exponential backoff<br>        <br>        raise RuntimeError(f&quot;All models failed. Last error: {last_error}&quot;)</pre><pre># Usage<br>fallback_middleware = ModelFallbackMiddleware(<br>    primary_model=ChatOpenAI(model=&quot;gpt-4o&quot;),<br>    fallback_models=[<br>        ChatOpenAI(model=&quot;gpt-4o-mini&quot;),<br>        ChatAnthropic(model=&quot;claude-3-haiku-20240307&quot;),<br>    ]<br>)</pre><h3>6. PII Protection: Keeping Sensitive Data Safe</h3><p>If your agent handles user conversations, you will inevitably encounter Personally Identifiable Information (PII): email addresses, phone numbers, credit card numbers, API keys, Aadhaar numbers, and more. Sending these directly to external LLM APIs is a compliance nightmare — and in some jurisdictions, a legal liability.</p><p><strong>PIIMiddleware</strong> scans every message before it hits the LLM and applies one of three strategies:</p><ul><li><strong>Block</strong>: Refuse to process the message entirely</li><li><strong>Redact</strong>: Strip the sensitive value, replace with [REDACTED]</li><li><strong>Mask</strong>: Replace with a reversible placeholder like [EMAIL_1] (useful for debugging)</li></ul><pre>import re<br>from enum import Enum<br>from dataclasses import dataclass, field</pre><pre>class PIIStrategy(Enum):<br>    BLOCK = &quot;block&quot;<br>    REDACT = &quot;redact&quot;<br>    MASK = &quot;mask&quot;</pre><pre>@dataclass<br>class PIIPattern:<br>    name: str<br>    pattern: str<br>    strategy: PIIStrategy<br>    description: str = &quot;&quot;</pre><pre>class PIIMiddleware:<br>    DEFAULT_PATTERNS = [<br>        PIIPattern(<br>            name=&quot;api_key&quot;,<br>            pattern=r&#39;\b(sk-[a-zA-Z0-9]{32,}|AIza[a-zA-Z0-9_-]{35}|AKIA[A-Z0-9]{16})\b&#39;,<br>            strategy=PIIStrategy.BLOCK,<br>            description=&quot;API Keys (OpenAI, Google, AWS)&quot;<br>        ),<br>        PIIPattern(<br>            name=&quot;credit_card&quot;,<br>            pattern=r&#39;\b(?:\d{4}[-\s]?){3}\d{4}\b&#39;,<br>            strategy=PIIStrategy.REDACT,<br>            description=&quot;Credit/Debit Card Numbers&quot;<br>        ),<br>        PIIPattern(<br>            name=&quot;email&quot;,<br>            pattern=r&#39;\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b&#39;,<br>            strategy=PIIStrategy.MASK,<br>            description=&quot;Email Addresses&quot;<br>        ),<br>        PIIPattern(<br>            name=&quot;phone_in&quot;,<br>            pattern=r&#39;\b(?:\+91[-\s]?)?[6-9]\d{9}\b&#39;,<br>            strategy=PIIStrategy.MASK,<br>            description=&quot;Indian Phone Numbers&quot;<br>        ),<br>        PIIPattern(<br>            name=&quot;aadhaar&quot;,<br>            pattern=r&#39;\b[2-9]\d{3}[\s-]?\d{4}[\s-]?\d{4}\b&#39;,<br>            strategy=PIIStrategy.REDACT,<br>            description=&quot;Aadhaar Numbers&quot;<br>        ),<br>        PIIPattern(<br>            name=&quot;pan_card&quot;,<br>            pattern=r&#39;\b[A-Z]{5}[0-9]{4}[A-Z]\b&#39;,<br>            strategy=PIIStrategy.REDACT,<br>            description=&quot;PAN Card Numbers&quot;<br>        ),<br>    ]<br>    <br>    def __init__(self, patterns: list[PIIPattern] = None, strict: bool = True):<br>        self.patterns = patterns or self.DEFAULT_PATTERNS<br>        self.strict = strict  # If True, BLOCK raises exception; if False, logs warning<br>        self._mask_registry: dict[str, dict[str, str]] = {}<br>    <br>    def process_text(self, text: str, thread_id: str = &quot;default&quot;) -&gt; str:<br>        &quot;&quot;&quot;Scan and sanitize a text string.&quot;&quot;&quot;<br>        if thread_id not in self._mask_registry:<br>            self._mask_registry[thread_id] = {}<br>        <br>        for pii in self.patterns:<br>            compiled = re.compile(pii.pattern, re.IGNORECASE)<br>            matches = compiled.findall(text)<br>            <br>            if not matches:<br>                continue<br>            <br>            if pii.strategy == PIIStrategy.BLOCK:<br>                if self.strict:<br>                    raise ValueError(<br>                        f&quot;🚫 Message blocked: Contains sensitive data of type &#39;{pii.name}&#39; &quot;<br>                        f&quot;({pii.description}). Remove it before sending.&quot;<br>                    )<br>                else:<br>                    print(f&quot;⚠️  WARNING: Potential {pii.description} detected.&quot;)<br>            <br>            elif pii.strategy == PIIStrategy.REDACT:<br>                text = compiled.sub(f&quot;[{pii.name.upper()}_REDACTED]&quot;, text)<br>            <br>            elif pii.strategy == PIIStrategy.MASK:<br>                registry = self._mask_registry[thread_id]<br>                <br>                def replace_with_mask(match):<br>                    value = match.group(0)<br>                    if value not in registry:<br>                        count = sum(1 for k in registry.values() <br>                                   if k.startswith(f&quot;[{pii.name.upper()}_&quot;))<br>                        registry[value] = f&quot;[{pii.name.upper()}_{count + 1}]&quot;<br>                    return registry[value]<br>                <br>                text = compiled.sub(replace_with_mask, text)<br>        <br>        return text<br>    <br>    def __call__(self, state: AgentState, config: dict) -&gt; AgentState:<br>        thread_id = config.get(&quot;configurable&quot;, {}).get(&quot;thread_id&quot;, &quot;default&quot;)<br>        messages = state.get(&quot;messages&quot;, [])<br>        <br>        sanitized_messages = []<br>        for msg in messages:<br>            if hasattr(msg, &quot;content&quot;) and isinstance(msg.content, str):<br>                clean_content = self.process_text(msg.content, thread_id)<br>                # Rebuild the message with sanitized content<br>                sanitized_msg = msg.__class__(content=clean_content)<br>                sanitized_messages.append(sanitized_msg)<br>            else:<br>                sanitized_messages.append(msg)<br>        <br>        return {**state, &quot;messages&quot;: sanitized_messages}</pre><p><strong>Example in action:</strong></p><pre>pii = PIIMiddleware()</pre><pre># This will be masked<br>print(pii.process_text(&quot;Email me at prashant@example.com&quot;))<br># → &quot;Email me at [EMAIL_1]&quot;</pre><pre># This will be redacted<br>print(pii.process_text(&quot;My Aadhaar is 2345 6789 0123&quot;))<br># → &quot;My Aadhaar is [AADHAAR_REDACTED]&quot;</pre><pre># This will BLOCK execution<br>pii.process_text(&quot;My API key is sk-abcdefghijklmnopqrstuvwxyz123456&quot;)<br># → ValueError: 🚫 Message blocked: Contains sensitive data of type &#39;api_key&#39;</pre><h3>7. Structured Outputs with Pydantic</h3><p>LLMs generate text. But production systems need data — structured, validated, typed data that can be stored in databases, consumed by APIs, or rendered in UIs. Pydantic bridges this gap.</p><p>By binding a Pydantic model to your LLM using .with_structured_output(), you instruct the LLM to return JSON that conforms to your schema — and you get automatic validation and a typed Python object back.</p><h3>A Real-World Example: Financial Analysis</h3><pre>from pydantic import BaseModel, Field, field_validator<br>from typing import Literal<br>from langchain_openai import ChatOpenAI</pre><pre>class RiskAssessment(BaseModel):<br>    &quot;&quot;&quot;Nested model for risk analysis.&quot;&quot;&quot;<br>    level: Literal[&quot;Low&quot;, &quot;Medium&quot;, &quot;High&quot;, &quot;Critical&quot;] = Field(<br>        description=&quot;Overall risk classification&quot;<br>    )<br>    factors: list[str] = Field(<br>        description=&quot;Key risk factors identified&quot;,<br>        min_length=1,<br>        max_length=10<br>    )<br>    mitigation: str = Field(<br>        description=&quot;Recommended risk mitigation strategy&quot;<br>    )</pre><pre>class FinancialAnalysis(BaseModel):<br>    &quot;&quot;&quot;Structured output for a financial analysis report.&quot;&quot;&quot;<br>    <br>    company_name: str = Field(description=&quot;Name of the company being analyzed&quot;)<br>    <br>    revenue_growth_pct: float = Field(<br>        description=&quot;Year-over-year revenue growth as a percentage&quot;<br>    )<br>    <br>    profit_margin_pct: float = Field(<br>        description=&quot;Net profit margin as a percentage&quot;<br>    )<br>    <br>    recommendation: Literal[&quot;Strong Buy&quot;, &quot;Buy&quot;, &quot;Hold&quot;, &quot;Sell&quot;, &quot;Strong Sell&quot;] = Field(<br>        description=&quot;Investment recommendation&quot;<br>    )<br>    <br>    key_strengths: list[str] = Field(<br>        description=&quot;Top 3 competitive strengths&quot;,<br>        min_length=1,<br>        max_length=5<br>    )<br>    <br>    key_concerns: list[str] = Field(<br>        description=&quot;Top concerns or red flags&quot;,<br>        min_length=1,<br>        max_length=5<br>    )<br>    <br>    risk: RiskAssessment = Field(description=&quot;Risk assessment details&quot;)<br>    <br>    target_price_inr: float | None = Field(<br>        default=None,<br>        description=&quot;12-month price target in INR, if applicable&quot;<br>    )<br>    <br>    summary: str = Field(<br>        description=&quot;2-3 sentence executive summary&quot;,<br>        max_length=500<br>    )<br>    <br>    @field_validator(&quot;revenue_growth_pct&quot;, &quot;profit_margin_pct&quot;)<br>    @classmethod<br>    def validate_percentage(cls, v: float) -&gt; float:<br>        if not -100 &lt;= v &lt;= 1000:<br>            raise ValueError(f&quot;Percentage {v} is outside realistic range [-100, 1000]&quot;)<br>        return round(v, 2)<br>    <br>    @field_validator(&quot;target_price_inr&quot;)<br>    @classmethod<br>    def validate_price(cls, v: float | None) -&gt; float | None:<br>        if v is not None and v &lt;= 0:<br>            raise ValueError(&quot;Target price must be positive&quot;)<br>        return v</pre><h3>Using Structured Output with LangGraph</h3><pre>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)</pre><pre># Bind the schema to the LLM<br>structured_llm = llm.with_structured_output(FinancialAnalysis)</pre><pre># Invoke with financial data<br>analysis: FinancialAnalysis = structured_llm.invoke(&quot;&quot;&quot;<br>Analyze this company:<br>- Company: TechCorp India Ltd<br>- Q4 Revenue: ₹450 Cr (up from ₹380 Cr YoY)<br>- Net Profit: ₹54 Cr<br>- Growing cloud division, but faces margin pressure from legacy products<br>- Strong management team, debt-free balance sheet<br>- Risk: High competition from global players entering Indian market<br>&quot;&quot;&quot;)</pre><pre># You now have a fully typed, validated Python object<br>print(f&quot;Company: {analysis.company_name}&quot;)<br>print(f&quot;Revenue Growth: {analysis.revenue_growth_pct}%&quot;)<br>print(f&quot;Recommendation: {analysis.recommendation}&quot;)<br>print(f&quot;Risk Level: {analysis.risk.level}&quot;)<br>print(f&quot;Summary: {analysis.summary}&quot;)</pre><pre># Store in database, send to API, render in UI — it&#39;s just a Python object</pre><p><strong>Output:</strong></p><pre>Company: TechCorp India Ltd<br>Revenue Growth: 18.42%<br>Recommendation: Buy<br>Risk Level: Medium<br>Summary: TechCorp India shows solid revenue growth of 18.4% YoY driven by cloud expansion,<br>with a healthy 12% profit margin and debt-free balance sheet. Management quality and<br>financial discipline are key strengths. Primary risk is increasing competitive pressure<br>from global cloud providers targeting the Indian enterprise market.</pre><h3>Why Structured Output Matters</h3><p>Without it, you get text that you have to parse with regex — brittle, error-prone, and unmaintainable. With Pydantic structured output:</p><ul><li><strong>Validation is automatic</strong> — invalid data raises ValidationError before it reaches your database</li><li><strong>Types are enforced</strong> — profit_margin_pct is always a float, never a string like &quot;12.5%&quot;</li><li><strong>Schema is self-documenting</strong> — your Pydantic model is the source of truth for what the LLM must return</li><li><strong>IDE support</strong> — full autocomplete, type checking, and refactoring support</li></ul><h3>8. Common Mistakes and How to Debug Them</h3><p>Building agents is full of subtle traps. Here are the most common ones — with fixes.</p><h3>❌ Mistake 1: Passing Strings Instead of Message Objects</h3><pre># WRONG — this will cause a cryptic error<br>result = agent.invoke({&quot;messages&quot;: [&quot;What is the weather?&quot;]})</pre><pre># CORRECT — always use message objects<br>result = agent.invoke({<br>    &quot;messages&quot;: [HumanMessage(content=&quot;What is the weather?&quot;)]<br>})</pre><p><strong>Symptom:</strong> AttributeError: &#39;str&#39; object has no attribute &#39;type&#39; or ValidationError on the messages field.</p><p><strong>Fix:</strong> LangGraph’s agent state schema expects BaseMessage objects. Import and use HumanMessage, AIMessage, etc. consistently.</p><h3>❌ Mistake 2: Forgetting thread_id</h3><pre># WRONG — stateless, memory never works<br>result = agent.invoke({&quot;messages&quot;: [HumanMessage(content=&quot;My name is Prashant.&quot;)]})</pre><pre># CORRECT — always pass config with thread_id<br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;user_session_42&quot;}}<br>result = agent.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=&quot;My name is Prashant.&quot;)]},<br>    config=config<br>)</pre><p><strong>Symptom:</strong> The agent forgets everything between turns. No error — it just silently starts fresh.</p><p><strong>Fix:</strong> Generate a UUID for each user session and always pass it. A good pattern: thread_id = f&quot;user_{user_id}_{session_id}&quot;.</p><h3>❌ Mistake 3: Python Case Sensitivity in Tool Names</h3><pre># Tool is defined as:<br>@tool<br>def GetWeather(city: str) -&gt; str:  # PascalCase<br>    ...</pre><pre># But called as:<br>tool_call = {&quot;name&quot;: &quot;get_weather&quot;, &quot;args&quot;: {&quot;city&quot;: &quot;Mumbai&quot;}}  # snake_case<br># → Tool not found!</pre><p><strong>Symptom:</strong> ToolNotFoundException or the agent&#39;s tool call silently returns an error message.</p><p><strong>Fix:</strong> LangChain converts tool names to lowercase snake_case by default. Name your tool functions in snake_case to begin with, and be consistent everywhere you reference them.</p><h3>❌ Mistake 4: Token Explosion Without Summarization</h3><pre># After 50 turns without summarization:<br>token_count = sum(len(m.content.split()) * 1.3 for m in state[&quot;messages&quot;])<br># → ~15,000 tokens per request × $0.01/1K tokens = $0.15 per message<br># × 1,000 users × 100 messages/day = $15,000/day — oops.</pre><p><strong>Symptom:</strong> Costs grow linearly with conversation length. Eventually: ContextWindowExceededError.</p><p><strong>Fix:</strong> Add SummarizationMiddleware that triggers every N messages. Set N based on your model&#39;s context window and cost tolerance. For GPT-4o with a 128K context, you can afford longer before summarizing — but you&#39;re still paying for every token.</p><h3>❌ Mistake 5: Synchronous Code in Async Agents</h3><pre># WRONG — blocks the event loop<br>result = agent.invoke(...)  # sync in an async context</pre><pre># CORRECT — use the async version<br>result = await agent.ainvoke(...)<br>async for chunk in agent.astream(...):<br>    ...</pre><p><strong>Symptom:</strong> Timeouts, slow responses, or the entire application hanging when serving multiple users concurrently.</p><p><strong>Fix:</strong> Always use ainvoke and astream when running inside an async function (FastAPI endpoint, async Jupyter cell, etc.).</p><h3>❌ Mistake 6: Not Handling Tool Errors Gracefully</h3><pre>@tool<br>def get_stock_price(ticker: str) -&gt; str:<br>    &quot;&quot;&quot;Get current stock price.&quot;&quot;&quot;<br>    response = requests.get(f&quot;https://api.stocks.example/{ticker}&quot;)<br>    return response.json()[&quot;price&quot;]  # Crashes if API is down or ticker is invalid</pre><p><strong>Fix:</strong> Wrap tool logic in try/except and return a meaningful error string. The agent can then decide to retry, use a different approach, or inform the user.</p><pre>@tool<br>def get_stock_price(ticker: str) -&gt; str:<br>    &quot;&quot;&quot;Get current stock price for a given ticker symbol.&quot;&quot;&quot;<br>    try:<br>        response = requests.get(<br>            f&quot;https://api.stocks.example/{ticker}&quot;,<br>            timeout=5<br>        )<br>        response.raise_for_status()<br>        return f&quot;Current price of {ticker}: ₹{response.json()[&#39;price&#39;]}&quot;<br>    except requests.Timeout:<br>        return f&quot;Error: Stock API timed out for {ticker}. Please try again.&quot;<br>    except requests.HTTPError as e:<br>        return f&quot;Error: Could not fetch price for {ticker} — {str(e)}&quot;<br>    except Exception as e:<br>        return f&quot;Unexpected error fetching {ticker}: {str(e)}&quot;</pre><h3>9. Best Practices for Production</h3><h3>Scalability</h3><ul><li><strong>Use PostgreSQL checkpointer in production.</strong> SqliteSaver is great for development, but SQLite doesn&#39;t handle concurrent writes well. Switch to PostgresSaver (from langgraph-checkpoint-postgres) for multi-instance deployments.</li><li><strong>Keep tool functions stateless.</strong> Tools should not hold in-memory state — that belongs in the agent’s message history or an external database.</li><li><strong>Shard by thread_id.</strong> If you’re running at scale, route conversations to specific workers based on thread_id hash to avoid checkpointer contention.</li></ul><h3>Cost Optimization</h3><ul><li><strong>Summarize aggressively for long conversations.</strong> A 10-message window with summarization can reduce costs by 70–90% for multi-turn chats.</li><li><strong>Use smaller models for tool calls.</strong> Route simple tool invocations (date formatting, simple calculations) to GPT-4o-mini; reserve GPT-4o for complex reasoning.</li><li><strong>Cache tool results.</strong> If get_weather(&quot;Mumbai&quot;) is called 5 times in the same conversation, cache the result for 5 minutes. Use functools.lru_cache or Redis.</li><li><strong>Set </strong><strong>max_tokens on your LLM.</strong> An unconstrained response can return 4,000 tokens when you needed 200. ChatOpenAI(model=&quot;gpt-4o&quot;, max_tokens=500).</li></ul><h3>Security</h3><ul><li><strong>Never log raw messages.</strong> Messages may contain PII. Log only metadata (thread_id, message count, latency, token count).</li><li><strong>Apply PIIMiddleware before any external call.</strong> Even if you trust your LLM provider, regulatory compliance (GDPR, DPDP Act in India) requires you to minimize data exposure.</li><li><strong>Validate all tool inputs.</strong> If a tool accepts a city name, validate it against an allowlist. Never pass unvalidated user input to a SQL query or shell command.</li><li><strong>Use secrets management.</strong> API keys should come from environment variables or a vault (AWS Secrets Manager, HashiCorp Vault) — never hardcoded.</li></ul><h3>Reliability</h3><ul><li><strong>Always implement ModelFallbackMiddleware.</strong> Primary model outages happen. A fallback to a smaller model is always better than a 500 error for your users.</li><li><strong>Set session-level call limits.</strong> Protect against runaway agents and prompt injection attacks that try to make the agent loop indefinitely.</li><li><strong>Implement circuit breakers.</strong> If a tool fails 3 times in a row within a session, disable it and inform the user rather than retrying forever.</li><li><strong>Monitor with LangSmith.</strong> LangChain’s official tracing tool gives you visibility into every step — token counts, latencies, tool calls, errors — without adding code.</li></ul><h3>The Production-Ready Stack</h3><p>A mature agent deployment looks like this:</p><pre>User Request<br>    ↓<br>FastAPI / Django (async endpoint)<br>    ↓<br>PIIMiddleware          ← Strip sensitive data FIRST<br>    ↓<br>ModelCallLimitMiddleware  ← Check budget before proceeding<br>    ↓<br>ToolCallLimitMiddleware   ← Check tool budgets<br>    ↓<br>SummarizationMiddleware   ← Compress context if needed<br>    ↓<br>LangGraph Agent          ← Core reasoning + tool calls<br>    ↓<br>ModelFallbackMiddleware   ← Wrap model invocations<br>    ↓<br>Structured Output (Pydantic) ← Parse + validate response<br>    ↓<br>PostgreSQL Checkpointer  ← Persist state<br>    ↓<br>Response to User</pre><p>Each layer has a single responsibility. Each can be tested, monitored, and replaced independently. That’s the architecture of a system that scales.</p><h3>10. Conclusion</h3><p>We’ve covered a lot of ground. Let’s zoom out.</p><p>Six months ago, “building an AI agent” meant calling the API and hoping for the best. Today, the tooling has matured to the point where production-grade agents are achievable for any engineering team — but only if you treat them as the distributed systems they are, not as chatbots with a fancy wrapper.</p><p>Here’s what you’ve learned to assemble:</p><ul><li><strong>LangChain + LangGraph</strong> give you the primitives: structured messages, tool calling, stateful graph execution</li><li><strong>SqliteSaver / PostgresSaver</strong> give you memory that survives restarts and scales with your user base</li><li><strong>Streaming</strong> gives your users the real-time experience they expect</li><li><strong>Middleware</strong> — summarization, call limits, fallbacks — gives you the operational control every production system needs</li><li><strong>PIIMiddleware</strong> ensures you’re compliant and responsible with sensitive data</li><li><strong>Pydantic structured outputs</strong> replace fragile text parsing with typed, validated data objects</li><li><strong>Knowing the common mistakes</strong> saves you hours of debugging and dollars of wasted API spend</li></ul><p>The most important shift is mental: stop thinking of your agent as a chatbot and start thinking of it as a service. It has SLAs, budgets, security requirements, and users who depend on it. Build accordingly.</p><p>The components in this article aren’t theoretical — they’re the exact patterns used in production systems handling thousands of conversations a day. Start with the basics, layer in complexity as you need it, and always ask: <em>“What happens when this fails?”</em></p><p>That question, more than any framework or library, is what separates a demo from a system.</p><h3>Full Dependency Reference</h3><pre>pip install langchain langchain-core langchain-openai langchain-anthropic<br>pip install langgraph langgraph-checkpoint-sqlite<br>pip install pydantic<br>pip install python-dotenv  # For environment variable management</pre><pre># Minimal production setup<br>import os<br>from dotenv import load_dotenv</pre><pre>load_dotenv()</pre><pre>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>ANTHROPIC_API_KEY = os.getenv(&quot;ANTHROPIC_API_KEY&quot;)</pre><pre># Never hardcode API keys. Never.</pre><p><em>If you found this article helpful, consider following me for more deep-dives into production AI engineering. Have questions or ran into an issue? Drop a comment — I read every one.</em></p><p><em>— Prashant Kumar</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13715a9a00e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OSGi Event Handler — The Foundation of AEM Event-Driven Architecture]]></title>
            <link>https://medium.com/@prashantx7979/osgi-event-handler-the-foundation-of-aem-event-driven-architecture-76530847f89c?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/76530847f89c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[event-handlers]]></category>
            <category><![CDATA[osgi]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 04:36:15 GMT</pubDate>
            <atom:updated>2026-02-09T04:36:15.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>OSGi Event Handler — The Foundation of AEM Event-Driven Architecture</h3><h3>🎯 Introduction: The Real-World Problem</h3><p>Imagine you’re working at a publishing company using Adobe Experience Manager (AEM). Your editor just published an article about “Top 10 Travel Destinations for 2026”. Within seconds, the following must happen:</p><ol><li><strong>Homepage</strong> needs to show the new article</li><li><strong>Cache</strong> must be invalidated (cleared)</li><li><strong>Social media</strong> team needs notification</li><li><strong>Email subscribers</strong> should receive alerts</li><li><strong>Analytics</strong> system needs to track the publication</li><li><strong>Search index</strong> must be updated</li><li><strong>Recommendation engine</strong> should include this article</li><li><strong>Audit logs</strong> must record who published what and when</li></ol><p><strong>The Wrong Way (Tightly Coupled):</strong></p><pre>public void publishArticle(Article article) {<br>    // Save article<br>    articleRepository.save(article);<br>    <br>    // Update homepage - PROBLEM: What if homepage service is down?<br>    homepageService.addArticle(article);<br>    <br>    // Clear cache - PROBLEM: What if cache service fails?<br>    cacheService.invalidate(article.getPath());<br>    <br>    // Notify social media - PROBLEM: What if this takes 30 seconds?<br>    socialMediaService.notify(article);<br>    <br>    // Send emails - PROBLEM: What if there are 10,000 subscribers?<br>    emailService.sendToSubscribers(article);<br>    <br>    // ... and so on<br>    // RESULT: Your publish button takes 2 minutes to respond!<br>    // RESULT: If ANY service fails, EVERYTHING fails!<br>}</pre><p><strong>The Right Way (Event-Driven with OSGi Events):</strong></p><pre>public void publishArticle(Article article) {<br>    // Save article<br>    articleRepository.save(article);<br>    <br>    // Fire an event and forget - responds in milliseconds!<br>    eventAdmin.postEvent(new Event(&quot;com/mycompany/article/PUBLISHED&quot;, properties));<br>    <br>    // Done! The user sees immediate response<br>    // All other services listen for this event and act independently<br>}</pre><p>This is the power of <strong>OSGi Event Handlers</strong>. Let’s understand how this works from the ground up.</p><h3>📚 Table of Contents</h3><ol><li><a href="#core-concepts">Core Concepts &amp; Theory</a></li><li><a href="#architecture">OSGi Event Admin Architecture</a></li><li><a href="#data-flow">Data Flow: How Events Travel</a></li><li><a href="#first-handler">Building Your First Event Handler</a></li><li><a href="#sync-async">Synchronous vs Asynchronous Processing</a></li><li><a href="#filtering">Event Filtering Strategies</a></li><li><a href="#real-world">Real-World Implementation</a></li><li><a href="#interview">Interview Questions &amp; Answers</a></li><li><a href="#performance">Performance Optimization</a></li><li><a href="#pitfalls">Common Pitfalls &amp; Solutions</a></li></ol><h3>The Publish-Subscribe Pattern (Pub-Sub)</h3><p><strong>Theory (Important for Interviews):</strong></p><p>The Pub-Sub pattern is a messaging pattern where:</p><ul><li><strong>Publishers</strong> emit events without knowing who will receive them</li><li><strong>Subscribers</strong> listen for events without knowing who sent them</li><li><strong>Broker</strong> (Event Admin Service) manages delivery</li></ul><p><strong>Benefits:</strong></p><ol><li><strong>Loose Coupling</strong>: Components are independent</li><li><strong>Scalability</strong>: Add/remove subscribers without changing publishers</li><li><strong>Reliability</strong>: One failure doesn’t break the entire system</li><li><strong>Maintainability</strong>: Each component has a single responsibility</li></ol><p><strong>Interview Question:</strong> <em>“Why use events instead of direct method calls?”</em></p><p><strong>Answer:</strong> Events provide:</p><ul><li><strong>Temporal Decoupling</strong>: Publisher and subscriber don’t need to be active at the same time</li><li><strong>Spatial Decoupling</strong>: Components can be on different servers</li><li><strong>Synchronization Decoupling</strong>: Asynchronous processing prevents blocking</li><li><strong>Failure Isolation</strong>: One handler’s failure doesn’t affect others</li></ul><h3>OSGi Event Admin Service Specification</h3><p><strong>Theory (OSGi R8 Specification):</strong></p><p>The Event Admin Service is defined in OSGi Compendium Release 8, Chapter 113. It defines:</p><p><strong>Event</strong> — An immutable object with:</p><ul><li>topic (String): Category/channel (e.g., &quot;com/mycompany/article/PUBLISHED&quot;)</li><li>properties (Map): Data payload</li></ul><p><strong>EventHandler</strong> — Interface with one method:</p><ul><li>handleEvent(Event event): Process the event</li></ul><p><strong>EventAdmin</strong> — Service with two methods:</p><ul><li>postEvent(Event): Asynchronous delivery</li><li>sendEvent(Event): Synchronous delivery</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SxXh_kIS2Rh8_KNRU2c3w.png" /></figure><h3>How the Architecture Works (Data Flow Explanation)</h3><p><strong>Step-by-Step Process:</strong></p><ol><li><strong>Event Creation</strong>: Publisher creates an Event object</li><li><strong>Event Submission</strong>: Publisher calls eventAdmin.postEvent() or sendEvent()</li><li><strong>Topic Matching</strong>: Event Admin checks Event Topic Registry</li><li><strong>Handler Selection</strong>: Finds all handlers registered for that topic</li><li><strong>Event Delivery</strong>:</li></ol><ul><li><strong>postEvent</strong>: Event goes to queue → Thread pool → Handler (async)</li><li><strong>sendEvent</strong>: Event goes directly to handler (sync)</li></ul><p><strong>6.Handler Execution</strong>: Each handler processes the event</p><p><strong>7.Completion</strong>: Control returns to publisher (for sendEvent) or continues (for postEvent)</p><h3>Data Flow: How Events Travel Through the System</h3><h3>Scenario: Publishing an Article</h3><p>Let’s trace how data moves when an article is published.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UMUVZwbw31s9bo9KFoykw.png" /></figure><h3>Understanding the Data Journey</h3><p><strong>1. Event Object Structure:</strong></p><pre>// This is what the Event object looks like internally<br>Event {<br>    topic: &quot;com/mycompany/article/PUBLISHED&quot;<br>    properties: {<br>        &quot;articlePath&quot;: &quot;/content/mysite/articles/travel-2026&quot;,<br>        &quot;articleTitle&quot;: &quot;Top 10 Travel Destinations for 2026&quot;,<br>        &quot;author&quot;: &quot;john.doe&quot;,<br>        &quot;timestamp&quot;: 1707206400000,<br>        &quot;category&quot;: &quot;travel&quot;,<br>        &quot;tags&quot;: [&quot;travel&quot;, &quot;2026&quot;, &quot;destinations&quot;]<br>    }<br>}</pre><p>2. How Data Reaches Each Handler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jks1hkKWfih7hEd7Tud8w.png" /></figure><h3>🧭 Role of the Topic Matcher</h3><h3>👉 What it is</h3><p>The <strong>Topic Matcher</strong> is the part of Event Admin that decides:</p><blockquote><em>“Which handlers are interested in this event?”</em></blockquote><p>Every event has a <strong>topic string</strong>, and every handler declares which topics it listens to.</p><p><strong>Handler</strong></p><p>An <strong>Event Handler</strong> is a component that listens to specific event topics and reacts when those events occur.<br> It receives the event object and extracts required properties from it.<br> Based on the event data, it executes a focused piece of business logic (like clearing cache or sending email).<br> Handlers enable loose coupling by separating event producers from event consumers.</p><h3>👨‍💻 Building Your First Event Handler: The Beginner’s Thinking Process</h3><h3>Scenario: Invalidate Cache When Article is Published</h3><p><strong>Business Requirement:</strong> “When an article is published, we need to clear the cache so users see the latest content immediately.”</p><h3>Step 1: Think Like a Beginner — What Do We Need?</h3><p><strong>Questions to Ask Yourself:</strong></p><ol><li><strong>What triggers this?</strong> → Article publication event</li><li><strong>What should happen?</strong> → Cache invalidation</li><li><strong>Do I need immediate response?</strong> → Yes, cache should clear quickly</li><li><strong>Can this fail without breaking publish?</strong> → Yes, publish should work even if cache fails</li></ol><p><strong>Conclusion:</strong> We need an Event Handler that listens for article publication events!</p><h3>Step 2: Understanding the Components Needed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiDoqPqq8zVikxeBXLGGsg.png" /></figure><h3>Step 3: Logic Building — Breaking Down the Problem</h3><p><strong>Think:</strong> “What does my handler need to do?”</p><ol><li><strong>Listen</strong> for the right events</li><li><strong>Extract</strong> the article path from the event</li><li><strong>Call</strong> the cache service to invalidate</li><li><strong>Handle</strong> errors gracefully</li><li><strong>Log</strong> what happened (for debugging)</li></ol><p><strong>Mental Model:</strong></p><pre>IF article published event received<br>    THEN extract article path<br>    THEN invalidate cache for that path<br>    IF error occurs<br>        THEN log error but don&#39;t crash<br>    END IF<br>END IF</pre><pre>package com.mycompany.core.eventhandlers;<br><br><br><br><br>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Reference;<br>import org.osgi.service.event.EventHandler;<br>import org.osgi.service.event.Event;<br>import org.osgi.service.event.EventConstants;<br><br>// Logger - To log what&#39;s happening (crucial for debugging!)<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>/**<br> * Cache Invalidation Event Handler<br> * <br> * PURPOSE: Listens for article publication events and invalidates cache<br> * <br> * WHY EVENT HANDLER? <br> * - We don&#39;t want to slow down the publish process<br> * - Cache invalidation should happen independently<br> * - If cache fails, publish should still succeed<br> * <br> * WHEN IS THIS CALLED?<br> * - Automatically by OSGi Event Admin when article is published<br> * <br> * @author Your Name<br> */<br><br>/<br>@Component(<br>    // OSGi will register it as an EventHandler service<br>    service = EventHandler.class,<br>    // We NEED this running immediately to catch events<br>    immediate = true,<br>    property = {<br>        // This is a FILTER that says: &quot;Only send me events with these topics&quot;<br>          EventConstants.EVENT_TOPIC + &quot;=com/mycompany/article/PUBLISHED&quot;,<br>        <br>        // You can listen to multiple topics:<br>        // EventConstants.EVENT_TOPIC + &quot;=com/mycompany/article/*&quot;<br>        // The * means: article/PUBLISHED, article/UPDATED, article/DELETED, etc<br>    }<br>)<br>public class CacheInvalidationEventHandler implements EventHandler {<br>    <br>    private static final Logger LOG = LoggerFactory.getLogger(CacheInvalidationEventHandler.class);<br>   <br>    <br>    <br>    @Reference<br>    private CacheService cacheService;<br>    <br>    /**<br>     * This method is called by Event Admin when an event matches our topic<br>     * <br>     * FLOW:<br>     * 1. Article Service publishes article<br>     * 2. Article Service fires event with topic &quot;com/mycompany/article/PUBLISHED&quot;<br>     * 3. Event Admin checks: &quot;Who wants this topic?&quot;<br>     * 4. Event Admin finds OUR handler (because we registered for this topic)<br>     * 5. Event Admin calls THIS method with the event object<br>     * <br>     * @param event - Contains all data about what happened<br>     */<br>    @Override<br>    public void handleEvent(Event event) {<br>        <br>        // STEP 1: LOG that we received the event<br>        // WHY? So we can verify in logs: &quot;Did the handler run?&quot;<br>        // In production, if something doesn&#39;t work, you check logs first!<br>        LOG.info(&quot;Received event with topic: {}&quot;, event.getTopic());<br>        <br>        // STEP 2: EXTRACT DATA from the event<br>        // Event is just a Map of properties<br>        // Publisher puts data in, we take it out<br>        <br>        // Get the article path<br>        // WHY String.class? getProperty returns Object, we need String<br>        // WHY &quot;articlePath&quot;? Publisher and handler must agree on key names!<br>        // This is like a contract: &quot;I&#39;ll put data with key &#39;articlePath&#39;, you read it&quot;<br>        String articlePath = (String) event.getProperty(&quot;articlePath&quot;);<br>        <br>        // DEFENSIVE PROGRAMMING - Always validate!<br>        // WHY? What if publisher forgot to set articlePath?<br>        // Without this check, we&#39;d get NullPointerException and crash<br>        if (articlePath == null || articlePath.isEmpty()) {<br>            LOG.error(&quot;Event does not contain articlePath property. Cannot invalidate cache.&quot;);<br>            <br>           <br>            return;<br>        }<br>        <br>        LOG.info(&quot;Invalidating cache for article: {}&quot;, articlePath);<br>        <br>        CALL THE CACHE SERVICE<br>        // This is the actual business logic!<br>        // Everything else is infrastructure<br>        <br>       <br>        try {<br>            cacheService.invalidate(articlePath);<br>           LOG.info(&quot;Successfully invalidated cache for: {}&quot;, articlePath);<br>            <br>        } catch (Exception e) {<br>            <br>            LOG.error(&quot;Failed to invalidate cache for article: {}. Error: {}&quot;, <br>                     articlePath, e.getMessage(), e);<br>            <br>            <br>        }<br>        <br>        <br>    }<br>}</pre><h3>🔄 Synchronous vs Asynchronous Processing: The Critical Difference</h3><h3>Theory: Understanding Threading Models</h3><p><strong>Interview Question:</strong> <em>“What’s the difference between postEvent() and sendEvent()?”</em></p><p>Synchronous Example (sendEvent):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*258bC-5kmscqh9S5bW5RPw.png" /></figure><pre>// Publisher code<br>public void publishArticle() {<br>    // Save article - takes 100ms<br>    repository.save(article);<br>    <br>    // Fire SYNCHRONOUS event<br>    eventAdmin.sendEvent(event);  // Blocks here!<br>    <br>    // sendEvent waits for ALL handlers:<br>    // Handler 1 (Cache): 50ms<br>    // Handler 2 (Email): 200ms  <br>    // Handler 3 (Analytics): 100ms<br>    // Total wait: 350ms<br>    <br>    // FINALLY returns to user<br>    // Total time: 100 + 350 = 450ms<br>}<br><br>// User Experience: Waits 450ms for response</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa2d0Led35OapKThg6TNaw.png" /></figure><p>Asynchronous Example (postEvent):</p><pre>// Publisher code<br>public void publishArticle() {<br>    // Save article - takes 100ms<br>    repository.save(article);<br>    <br>    // Fire ASYNCHRONOUS event<br>    eventAdmin.postEvent(event);  // Returns immediately!<br>    <br>    // Event goes to background queue<br>    // Handlers process in parallel, in background<br>    <br>    // Returns to user NOW<br>    // Total time: 100ms + ~2ms = 102ms<br>}<br><br>// User Experience: Waits only 102ms for response!<br>// Handlers process in background (user doesn&#39;t wait)</pre><h3>When to Use Each?</h3><p><strong>Use sendEvent() (Synchronous) When:</strong></p><ol><li><strong>You need results immediately</strong></li></ol><pre>// Example: Validation that must happen NOW<br>   Event validationEvent = new Event(&quot;validate/article&quot;, props);<br>   eventAdmin.sendEvent(validationEvent);<br>   <br>   // Check if validation failed (handlers set this)<br>   if (props.get(&quot;validationFailed&quot;) == Boolean.TRUE) {<br>       throw new ValidationException(&quot;Article invalid&quot;);<br>   }</pre><ol><li><strong>Order matters</strong></li></ol><pre>// Handler 1 must complete before Handler 2<br>   // Example: Create user, then create user&#39;s folder</pre><ol><li><strong>Transaction coordination</strong></li></ol><pre>// All handlers must complete in same transaction</pre><p><strong>Use postEvent() (Asynchronous) When:</strong></p><ol><li><strong>User doesn’t need to wait</strong> (99% of cases!)</li></ol><pre>// Examples:<br>   // - Sending emails<br>   // - Updating analytics<br>   // - Invalidating cache<br>   // - Generating reports</pre><ol><li><strong>Independent operations</strong></li></ol><pre>// Handlers don&#39;t depend on each other<br>   // Can run in parallel</pre><ol><li><strong>Performance is critical</strong></li></ol><pre>// User-facing operations<br>   // Must respond quickly</pre><h3>Code Comparison</h3><pre>/**<br> * PUBLISHING SERVICE - Choosing the Right Method<br> */<br>@Component(service = ArticleService.class)<br>public class ArticleServiceImpl implements ArticleService {<br>    <br>    @Reference<br>    private EventAdmin eventAdmin;<br>    <br>    /**<br>     * BAD: Using sendEvent for notifications<br>     * User waits for ALL email sending to complete!<br>     */<br>    public void publishArticle_WRONG(Article article) {<br>        repository.save(article);<br>        <br>        Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br>        props.put(&quot;articlePath&quot;, article.getPath());<br>        <br>        // WRONG: Synchronous for notifications<br>        // User waits for email service (could be 5 seconds!)<br>        eventAdmin.sendEvent(new Event(&quot;article/PUBLISHED&quot;, props));<br>        <br>        // Returns after ALL handlers complete<br>        // SLOW user experience<br>    }<br>    <br>    /**<br>     * GOOD: Using postEvent for notifications<br>     * User gets immediate response<br>     */<br>    public void publishArticle_CORRECT(Article article) {<br>        repository.save(article);<br>        <br>        Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br>        props.put(&quot;articlePath&quot;, article.getPath());<br>        <br>        // CORRECT: Asynchronous for notifications<br>        // Returns immediately, handlers process in background<br>        eventAdmin.postEvent(new Event(&quot;article/PUBLISHED&quot;, props));<br>        <br>        // User sees instant response!<br>    }<br>    <br>    /**<br>     * CORRECT: Using sendEvent for validation<br>     * We NEED to know if validation failed<br>     */<br>    public void saveArticle_NeedsValidation(Article article) {<br>        Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br>        props.put(&quot;article&quot;, article);<br>        props.put(&quot;validationPassed&quot;, Boolean.TRUE);<br>        <br>        // CORRECT: Synchronous for validation<br>        // Validation handlers run NOW<br>        eventAdmin.sendEvent(new Event(&quot;article/VALIDATE&quot;, props));<br>        <br>        // Check result<br>        if (props.get(&quot;validationPassed&quot;) == Boolean.FALSE) {<br>            String errors = (String) props.get(&quot;validationErrors&quot;);<br>            throw new ValidationException(errors);<br>        }<br>        <br>        // Validation passed, save article<br>        repository.save(article);<br>    }<br>}</pre><h3>Event Filtering Strategies: Getting Only What You Need</h3><h3>Theory: Why Filtering Matters</h3><p>Imagine a busy restaurant kitchen:</p><ul><li><strong>No Filtering</strong>: Every cook hears every order (chaos!)</li><li><strong>With Filtering</strong>: Grill cook only hears grill orders (efficient!)</li></ul><p>Event filtering ensures handlers only receive relevant events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfBtJkVwJ08xkqm-88IerA.png" /></figure><p><strong>LDAP Filter Syntax:</strong></p><p>OSGi uses LDAP filter syntax (from LDAP directory services). It’s powerful but looks strange at first.</p><p><strong>Basic Syntax:</strong></p><ul><li>(property=value) - equals</li><li>(property&gt;=value) - greater than or equal</li><li>(property&lt;=value) - less than or equal</li><li>(!(property=value)) - not equals</li><li>(&amp;(prop1=val1)(prop2=val2)) - AND</li><li>(|(prop1=val1)(prop2=val2)) - OR</li></ul><h3>🌍 Real-World Implementation: Complete E-Commerce Example</h3><h3>Scenario: Complete Product Purchase Flow</h3><p>Let’s build a realistic e-commerce system with multiple event handlers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igeHRAU9jFqn7JVY0wzZIA.png" /></figure><p>Implementation: Order Service (Publisher)</p><pre>package com.ecommerce.core.services.impl;<br><br>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Reference;<br>import org.osgi.service.event.Event;<br>import org.osgi.service.event.EventAdmin;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>/**<br> * Order Service - Handles order creation and publishes events<br> * <br> * ROLE: This is the PUBLISHER in our event system<br> * <br> * WHY EVENTS?<br> * - Order creation triggers many downstream actions<br> * - We don&#39;t want to slow down the purchase process<br> * - Each action (email, shipping, analytics) should be independent<br> * - If one fails, others should still work<br> * <br> * THINKING PROCESS:<br> * 1. User buys product - needs fast response<br> * 2. Many things must happen (email, shipping, etc.)<br> * 3. User shouldn&#39;t wait for all of them<br> * 4. Solution: Fire event and let handlers work in background<br> */<br>@Component(service = OrderService.class)<br>public class OrderServiceImpl implements OrderService {<br>    <br>    private static final Logger LOG = LoggerFactory.getLogger(OrderServiceImpl.class);<br>    <br>    // Topic name - This is our &quot;event channel&quot;<br>    // Convention: company/domain/action<br>    private static final String ORDER_CREATED_TOPIC = &quot;com/ecommerce/order/CREATED&quot;;<br>    <br>    @Reference<br>    private EventAdmin eventAdmin;<br>    <br>    @Reference<br>    private OrderRepository orderRepository;<br>    <br>    /**<br>     * Create an order and publish event<br>     * <br>     * FLOW:<br>     * 1. Save order to database<br>     * 2. Create event with order data<br>     * 3. Fire event (async)<br>     * 4. Return immediately to customer<br>     * 5. Handlers process in background<br>     */<br>    @Override<br>    public Order createOrder(OrderRequest request) {<br>        LOG.info(&quot;Creating order for customer: {}&quot;, request.getCustomerId());<br>        <br>        // STEP 1: Create and save order<br>        // This is the essential work - must succeed<br>        Order order = new Order();<br>        order.setCustomerId(request.getCustomerId());<br>        order.setProductId(request.getProductId());<br>        order.setQuantity(request.getQuantity());<br>        order.setTotalAmount(request.getTotalAmount());<br>        order.setTimestamp(System.currentTimeMillis());<br>        order.setStatus(&quot;CREATED&quot;);<br>        <br>        // Save to database<br>        orderRepository.save(order);<br>        LOG.info(&quot;Order saved with ID: {}&quot;, order.getId());<br>        <br>        // STEP 2: Publish event<br>        // This notifies all interested parties<br>        publishOrderCreatedEvent(order);<br>        <br>        // STEP 3: Return immediately<br>        // Customer sees instant response!<br>        // All background processing happens via event handlers<br>        return order;<br>    }<br>    <br>    /**<br>     * Publish order created event<br>     * <br>     * WHY SEPARATE METHOD?<br>     * - Cleaner code organization<br>     * - Easier to test<br>     * - Can reuse for other scenarios<br>     * <br>     * EVENT PAYLOAD DESIGN:<br>     * - Include all data handlers might need<br>     * - Use primitive types when possible (for LDAP filtering)<br>     * - Use consistent naming<br>     */<br>    private void publishOrderCreatedEvent(Order order) {<br>        // Create event properties<br>        // Think: &quot;What data do handlers need?&quot;<br>        Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;();<br>        <br>        // Order identification<br>        properties.put(&quot;orderId&quot;, order.getId());<br>        properties.put(&quot;timestamp&quot;, order.getTimestamp());<br>        <br>        // Customer information<br>        properties.put(&quot;customerId&quot;, order.getCustomerId());<br>        properties.put(&quot;customerEmail&quot;, order.getCustomerEmail());<br>        properties.put(&quot;customerName&quot;, order.getCustomerName());<br>        <br>        // Product information<br>        properties.put(&quot;productId&quot;, order.getProductId());<br>        properties.put(&quot;productName&quot;, order.getProductName());<br>        properties.put(&quot;quantity&quot;, order.getQuantity());<br>        <br>        // Financial information<br>        properties.put(&quot;totalAmount&quot;, order.getTotalAmount());<br>        properties.put(&quot;currency&quot;, order.getCurrency());<br>        <br>        // Additional metadata<br>        properties.put(&quot;shippingAddress&quot;, order.getShippingAddress());<br>        properties.put(&quot;source&quot;, &quot;web&quot;); // web, mobile, api<br>        properties.put(&quot;priority&quot;, determinePriority(order)); // For filtering<br>        <br>        // Create event object<br>        Event event = new Event(ORDER_CREATED_TOPIC, properties);<br>        <br>        // Publish asynchronously<br>        // WHY postEvent not sendEvent?<br>        // - We don&#39;t need to wait for handlers<br>        // - User gets instant response<br>        // - Handlers work in background<br>        // - Better performance<br>        eventAdmin.postEvent(event);<br>        <br>        LOG.info(&quot;Published ORDER_CREATED event for order: {}&quot;, order.getId());<br>    }<br>    <br>    /**<br>     * Determine order priority for filtering<br>     * <br>     * WHY?<br>     * - Some handlers only care about high-value orders<br>     * - Can filter using: (priority&gt;=8)<br>     * - More efficient than processing all orders<br>     */<br>    private int determinePriority(Order order) {<br>        if (order.getTotalAmount() &gt; 1000) {<br>            return 10; // High priority<br>        } else if (order.getTotalAmount() &gt; 500) {<br>            return 7; // Medium priority<br>        } else {<br>            return 5; // Normal priority<br>        }<br>    }<br>}</pre><h3>Question 1: Explain OSGi Event Admin Service</h3><p><strong>Answer:</strong></p><p>“OSGi Event Admin Service is a publish-subscribe messaging system built into OSGi. It provides asynchronous event-based communication between bundles.</p><p><strong>Key Components:</strong></p><ul><li><strong>Event</strong>: Immutable object containing a topic (string) and properties (map)</li><li><strong>EventAdmin</strong>: Central service that routes events</li><li><strong>EventHandler</strong>: Interface that components implement to receive events</li></ul><p><strong>How it works:</strong></p><ol><li>Publisher creates an Event and sends it to EventAdmin</li><li>EventAdmin matches the event’s topic against registered handlers</li><li>EventAdmin delivers the event to matching handlers</li><li>Handlers process the event independently</li></ol><p><strong>Benefits:</strong></p><ul><li><strong>Loose coupling</strong>: Publishers and subscribers don’t know about each other</li><li><strong>Scalability</strong>: Easy to add new handlers without modifying existing code</li><li><strong>Reliability</strong>: One handler’s failure doesn’t affect others</li><li><strong>Performance</strong>: Asynchronous processing doesn’t block the publisher</li></ul><p><strong>Real-world example:</strong> When a user publishes an article, we fire an event. Multiple handlers independently handle cache invalidation, email notifications, search indexing, and analytics — all without the publish operation knowing about any of them.”</p><h3>Question 2: postEvent vs sendEvent — When to use each?</h3><p><strong>Answer:</strong></p><p>“This is a critical performance decision.</p><p><strong>postEvent (Asynchronous):</strong></p><ul><li>Returns immediately, event is queued</li><li>Handlers execute in background thread pool</li><li>Publisher doesn’t wait for handlers to complete</li><li>Use for: notifications, logging, cache invalidation, emails — anything where publisher doesn’t need results</li></ul><p><strong>Example:</strong> User publishes article. postEvent returns in 2ms. Email handler takes 3 seconds but runs in background. User sees instant response.</p><p><strong>sendEvent (Synchronous):</strong></p><ul><li>Blocks until ALL handlers complete</li><li>Handlers execute in publisher’s thread</li><li>Publisher waits for results</li><li>Use for: validation, data enrichment, transaction coordination — anything where publisher needs results</li></ul><p><strong>Example:</strong> User submits form. sendEvent calls validation handlers. If validation fails, form shows errors. Publisher needs to know validation result before proceeding.</p><p><strong>Performance Impact:</strong></p><ul><li>System with 5 handlers, each taking 100ms</li><li>postEvent: Publisher waits ~2ms</li><li>sendEvent: Publisher waits ~500ms</li><li>250x performance difference!</li></ul><p><strong>Best Practice:</strong> Use postEvent for 95% of cases. Only use sendEvent when you absolutely need synchronous results.”</p><h3>Summary</h3><h3>Key Takeaways</h3><ol><li><strong>OSGi Event Admin</strong> is the foundation of event-driven architecture in AEM</li><li><strong>Use postEvent()</strong> for 95% of cases (async, non-blocking)</li><li><strong>Use sendEvent()</strong> only when you need synchronous results</li><li><strong>Filter events</strong> at Event Admin level for best performance</li><li><strong>Never throw exceptions</strong> from handlers — isolate failures</li><li><strong>Always validate</strong> event properties before using them</li><li><strong>Use immediate=true</strong> to ensure handlers activate</li><li><strong>Monitor performance</strong> — handlers should complete quickly</li></ol><h3>When to Use OSGi Events</h3><p>✅ <strong>Use OSGi Events when:</strong></p><ul><li>Multiple components need to react to same action</li><li>Operations can happen asynchronously</li><li>You want loose coupling</li><li>Components might be added/removed dynamically</li></ul><p>❌ <strong>Don’t Use OSGi Events when:</strong></p><ul><li>Synchronous response needed (use direct method call)</li><li>Only one component needs the data</li><li>Performance critical path (events add overhead)</li><li>Complex return values needed</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76530847f89c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This comprehensive guide explores AEM workflows through real-world scenarios, intuitive diagrams…]]></title>
            <link>https://medium.com/@prashantx7979/this-comprehensive-guide-explores-aem-workflows-through-real-world-scenarios-intuitive-diagrams-428e69cda3d3?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/428e69cda3d3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 07:02:18 GMT</pubDate>
            <atom:updated>2026-01-30T07:02:18.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>This comprehensive guide explores AEM workflows through real-world scenarios, intuitive diagrams, and clear illustrations — so you don’t just understand the flow, you feel it.”</h3><p>After years of building, breaking, and fixing Adobe Experience Manager (AEM) workflows in enterprise environments, I’ve learned that workflows are like the nervous system of your content management — invisible when working well, catastrophic when broken. Let me share everything I wish someone had told me on day one.</p><h3>🎯 What Exactly IS an AEM Workflow? (The Non-Jargon Version)</h3><p>Real-Life Analogy: The Restaurant Kitchen</p><p>Think of an AEM workflow like a restaurant kitchen during dinner service. When a customer places an order (content request), it doesn’t magically appear on their table. Instead:</p><ul><li>The waiter takes the order and passes it to the kitchen (workflow initiator)</li><li>The head chef assigns tasks to different stations (workflow steps)</li><li>Appetizer station → Main course station → Dessert station (sequential steps)</li><li>Quality check before serving (approval step)</li><li>Finally, the dish reaches the customer (content published)</li></ul><p>Just like in a kitchen, if one station breaks down, the entire service grinds to a halt. That’s why understanding workflows is crucial.</p><h3>Breaking Down the Jargon</h3><p>Let’s demystify the terms you’ll encounter:</p><p>Key Terminology Decoded</p><ul><li>Workflow Model: The blueprint or recipe that defines what steps happen and in what order. Think of it as the instruction manual.</li><li>Workflow Instance: An actual running execution of that blueprint. When someone clicks “Submit for Approval,” you create an instance.</li><li>Workflow Step: A single action or decision point in the process (like “Review Content” or “Translate to French”).</li><li>Payload: The actual content being processed through the workflow. Usually a page or asset.</li><li>Participant: A person or group responsible for completing a workflow step.</li><li>Launcher: An automatic trigger that starts a workflow when certain conditions are met (like “when a page is created”).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*0jrG8VXI89HKjLs__J8jig.png" /></figure><h3>🏗️ Real-World Example: Content Approval Workflow</h3><p>Let me walk you through a real workflow I built for a Fortune 500 client. They needed a three-tier approval process for their marketing content before it could go live on their public website.</p><h3>The Business Requirement</h3><p>Client Scenario: Global Retail Company</p><p>Problem: Content was going live without proper legal and brand compliance reviews, leading to inconsistent messaging and potential legal issues.</p><p>Solution Needed: Every marketing page must be approved by Content Editor → Brand Manager → Legal Team before publication.</p><p>Special Requirements: Legal team must review within 24 hours, automatic escalation if delayed.</p><h3>The Workflow Design: Step by Step</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*YN8et5ncID7UjYX3V6pu7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*dsuURmad6NKLJJ0oeNFOPA.png" /></figure><h3>The Technical Implementation</h3><p>Here’s how this translates into actual AEM workflow configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Qoy3hn5_Owwj4zXMBZT6tA.png" /></figure><h3>⚙️ The Technical Deep Dive: How Workflows Actually Work</h3><h3>The Workflow Execution Engine</h3><p>Analogy: The Orchestra Conductor</p><p>The workflow engine is like a conductor in an orchestra. It doesn’t play instruments itself, but it:</p><ul><li>Knows the entire score (workflow model)</li><li>Signals each musician when to play (triggers workflow steps)</li><li>Coordinates timing between sections (manages step transitions)</li><li>Handles mistakes gracefully (error handling and rollback)</li><li>Keeps the performance moving (monitors progress)</li></ul><h3>Understanding the Workflow Equation</h3><p>Here’s a simplified mental model of how workflow execution works:</p><p>The Workflow Execution Formula</p><p>Workflow Instance = Model + Payload + Metadata</p><p>Execution Time = Σ(Step Processing Time) + Queue Wait Time</p><p>Success Rate = (Completed Instances / Total Instances) × 100</p><p>Breaking it down:</p><ul><li>Model: The template defining all steps and logic</li><li>Payload: The content being processed (e.g., /content/site/page)</li><li>Metadata: Additional data like assignee, priority, due date</li><li>Queue Wait Time: Often the biggest bottleneck in enterprise systems</li></ul><h3>The Workflow Lifecycle</h3><p>1. Initiation</p><p>Workflow launcher detects trigger condition (manual or automatic). Creates new workflow instance in RUNNING state. Assigns unique instance ID and stores in JCR repository at /var/workflow/instances.</p><p>2. Execution</p><p>Engine reads next step from model. Executes process or creates participant task. Updates instance metadata with current state. Logs all actions for audit trail.</p><p>3. Transition</p><p>Evaluates route conditions (if step has multiple paths). Moves to next step based on user action or process result. Updates workflow history node.</p><p>4. Completion</p><p>All steps executed successfully. Instance marked as COMPLETED. Final processes run (notifications, cleanup). Instance archived for reporting.</p><h3>💼 Real-World Scenarios I’ve Encountered</h3><h3>Scenario 1: The Translation Nightmare</h3><p>The Problem</p><p>A global automotive client needed content translated into 27 languages. Their manual process took 6 weeks per campaign. Translators didn’t know what needed translating, content got lost, and deadlines were constantly missed.</p><p>The Solution</p><p>I built a workflow that:</p><ul><li>Automatically detected when English content was published</li><li>Created 27 language copies with proper folder structure</li><li>Assigned each language to specific translation teams</li><li>Tracked progress with visual dashboard</li><li>Auto-published translations when approved</li><li>Sent reminder emails if translations were delayed</li></ul><p>Result: Translation time reduced from 6 weeks to 10 days. Translation accuracy improved 40% due to better context and coordination.</p><h3>🛠️ Building Your First Custom Workflow: A Practical Guide</h3><h3>Step 1: Define the Business Process</h3><p>Before touching code, map out the process on paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*7X1LpsxeBfxCdAJtWVJagQ.png" /></figure><h3>Step 2: Choose Your Step Types</h3><p>AEM offers several step types, each serving different purposes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*5_EifvWF3sfXpftmoOosBg.png" /></figure><h3>Step 3: Create a Custom Process Step</h3><p>Here’s a real example of a custom process I wrote to watermark images:</p><pre>package com.company.workflow;<br><br>import com.day.cq.dam.api.Asset;<br>import com.day.cq.workflow.WorkflowException;<br>import com.day.cq.workflow.WorkflowSession;<br>import com.day.cq.workflow.exec.WorkItem;<br>import com.day.cq.workflow.exec.WorkflowProcess;<br>import com.day.cq.workflow.metadata.MetaDataMap;<br><br>import org.apache.sling.api.resource.Resource;<br>import org.apache.sling.api.resource.ResourceResolver;<br>import org.osgi.service.component.annotations.Component;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>@Component(<br>    service = WorkflowProcess.class,<br>    property = {<br>        &quot;process.label=Add Watermark to Image&quot;<br>    }<br>)<br>public class WatermarkProcess implements WorkflowProcess {<br><br>    private static final Logger LOG = LoggerFactory.getLogger(WatermarkProcess.class);<br><br>    @Override<br>    public void execute(<br>            WorkItem workItem,<br>            WorkflowSession workflowSession,<br>            MetaDataMap metaDataMap) throws WorkflowException {<br><br>        // 1. Get payload path (asset path)<br>        String payloadPath = workItem.getWorkflowData().getPayload().toString();<br><br>        // 2. Get process arguments (configured in workflow step)<br>        String watermarkText = metaDataMap.get(&quot;watermarkText&quot;, &quot;CONFIDENTIAL&quot;);<br><br>        try {<br>            // 3. Get ResourceResolver from WorkflowSession<br>            ResourceResolver resolver = workflowSession.adaptTo(ResourceResolver.class);<br><br>            if (resolver == null) {<br>                throw new WorkflowException(&quot;Unable to obtain ResourceResolver&quot;);<br>            }<br><br>            // 4. Get resource from payload path<br>            Resource resource = resolver.getResource(payloadPath);<br><br>            if (resource == null) {<br>                LOG.warn(&quot;No resource found at path: {}&quot;, payloadPath);<br>                return;<br>            }<br><br>            // 5. Adapt resource to Asset<br>            Asset asset = resource.adaptTo(Asset.class);<br><br>            if (asset == null) {<br>                LOG.warn(&quot;Resource is not an asset: {}&quot;, payloadPath);<br>                return;<br>            }<br><br>            // 6. Apply watermark<br>            applyWatermark(asset, watermarkText);<br><br>            LOG.info(&quot;Watermark &#39;{}&#39; applied successfully to asset: {}&quot;,<br>                    watermarkText, payloadPath);<br><br>        } catch (Exception e) {<br>            LOG.error(&quot;Error applying watermark to asset: {}&quot;, payloadPath, e);<br>            throw new WorkflowException(&quot;Failed to apply watermark&quot;, e);<br>        }<br>    }<br><br>    /**<br>     * Applies watermark to the given asset.<br>     * Actual image processing logic should be implemented here.<br>     */<br>    private void applyWatermark(Asset asset, String watermarkText) {<br>        // TODO:<br>        // - Read original rendition<br>        // - Use ImageIO / ThumbnailProcess / external library<br>        // - Apply text or image watermark<br>        // - Save new rendition or overwrite existing one<br>    }<br>}</pre><h3>⚡ Performance Optimization: Lessons Learned the Hard Way</h3><h3>The Performance Equation</h3><p>Critical Performance Formula</p><p>Total Processing Time = (Number of Steps × Average Step Time) + Repository I/O + Network Latency</p><p>Throughput = (Available Threads / Avg Workflow Duration) × 3600 workflows/hour</p><p>Bottleneck Impact = Slowest Step Time × Number of Sequential Dependencies</p><h4><strong>Common Performance Killers</strong></h4><ol><li>Repository Queries in Loops: I once saw a workflow query the JCR 1000 times per execution. Changed to a single query with predicates — went from 45 seconds to 2 seconds.</li><li>Synchronous External API Calls: Don’t wait for external systems in workflow steps. Use async processing or message queues.</li><li>Large Payload Processing: Processing 500MB video files in workflow steps brought the system to its knees. Solution: offload to dedicated processing servers.</li><li>Inefficient Participant Resolution: Dynamic participant choosers can be slow. Cache group memberships when possible.</li></ol><h3>🐛 Debugging: The Detective Work</h3><h3>The Debugging Toolkit</h3><p>Analogy: Medical Diagnosis</p><p>Debugging workflows is like diagnosing a patient:</p><ul><li>Symptoms: “Workflow stuck” or “content not publishing”</li><li>Vital Signs: Check workflow console for instance status</li><li>Medical History: Review workflow history and audit logs</li><li>Lab Tests: Enable DEBUG logging for specific packages</li><li>Treatment: Fix code, restart instance, or manual intervention</li></ul><h3>Real Debugging Scenarios</h3><p><strong>Problem: Workflow Stuck at Step 3</strong></p><p>Symptoms: Instance shows RUNNING but hasn’t progressed in 2 hours.</p><p>Diagnosis: Checked /var/workflow/instances node. Found participant step with no assignee.</p><p>Root Cause: Dynamic participant chooser returned null because user group was deleted.</p><p>Fix: Added null checking in participant chooser with fallback to admin group.</p><p><strong><em>Problem: Workflows Failing Silently</em></strong></p><p>Symptoms: Instance marked COMPLETED but content not published.</p><p>Diagnosis: Enabled DEBUG logging: com.day.cq.workflow=DEBUG</p><p>Root Cause: Process step catching exceptions but not rethrowing WorkflowException.</p><p>Fix: Proper exception handling and status reporting in all custom processes.</p><h3>🎓 Best Practices: The Wisdom of Experience</h3><p><strong>Golden Rules I Follow</strong></p><ol><li>Keep Steps Atomic: Each step should do ONE thing well. Makes debugging and reuse much easier.</li><li>Always Have Error Handling: Every custom process must catch exceptions and provide meaningful error messages.</li><li>Use Workflow Variables: Store intermediate data in workflow metadata, not in the payload. Keeps content clean.</li><li>Test with Real Data: Synthetic test data never reveals the edge cases production will throw at you.</li><li>Version Your Models: Keep old versions when making changes. Rollback is a lifesaver.</li><li>Document Everything: Your future self (and teammates) will thank you. Include business context, not just technical details.</li><li>Monitor Production: Set up alerts before you need them. Don’t wait for users to report issues.</li><li>Plan for Scale: Design for 10x your current volume. Growth happens faster than you think.</li></ol><p><strong>Mistakes I’ve Made (So You Don’t Have To)</strong></p><ol><li>Not Purging Old Instances: Accumulated 500,000 completed workflow instances. Repository performance tanked. Now we auto-purge instances older than 90 days.</li><li>Hardcoding Paths: Hardcoded /content/mysite everywhere. When client wanted multi-tenancy, had to refactor everything. Use variables and configuration.</li><li>Ignoring Transient Dependencies: One external system went down, took our entire workflow infrastructure with it. Always build in fallbacks and circuit breakers.</li><li>Over-Engineering: Built a 15-step workflow when a 4-step would suffice. Simpler is almost always better.</li><li>No Rollback Plan: Deployed a workflow change to production Friday afternoon. It broke. Spent weekend manually fixing 1,000 stuck instances. Always have a rollback strategy.</li></ol><h3>🔐 Security Considerations</h3><p>Security Vulnerabilities I’ve Seen</p><ol><li>Privilege Escalation: Workflow ran with admin privileges, allowing users to publish content they shouldn’t access. Always use service users with minimal permissions.</li><li>Information Disclosure: Workflow metadata contained PII visible to all users. Sanitize sensitive data, use encryption where needed.</li><li>Injection Attacks: User input from workflow dialog concatenated directly into queries. Always validate and sanitize inputs.</li><li>Missing Authorization: No checks if user should be able to start workflow. Implement proper ACLs and permission checks.</li></ol><h3>🎬 Final Thoughts</h3><p>After years of building AEM workflows, I’ve learned that the best workflows are the ones users don’t notice. They’re invisible infrastructure that makes content operations smooth and efficient.</p><p>The journey from simple approval workflows to complex, multi-tenant, international content orchestration systems has taught me that success comes from:</p><ul><li>Understanding the business need before writing code</li><li>Building incrementally and validating with real users</li><li>Monitoring relentlessly and optimizing based on data</li><li>Failing fast and learning from mistakes</li><li>Documenting everything for future maintainers</li></ul><p>Remember: workflows are tools to solve business problems. The fanciest, most technically impressive workflow is useless if it doesn’t make someone’s job easier or the business more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=428e69cda3d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AEM Dispatcher: The Complete Guide from Zero to Hero]]></title>
            <link>https://medium.com/@prashantx7979/aem-dispatcher-the-complete-guide-from-zero-to-hero-98a666a04ace?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a666a04ace</guid>
            <category><![CDATA[adobe]]></category>
            <category><![CDATA[dispatcher]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 05:05:05 GMT</pubDate>
            <atom:updated>2026-01-14T05:05:05.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*exENnKK93Byq7W31" /></figure><p>If you’re working with Adobe Experience Manager, understanding the <strong>Dispatcher</strong> is non-negotiable. It’s the gatekeeper between your users and your AEM instances, responsible for caching, load balancing, and security. Yet, many developers struggle with its configuration and troubleshooting.</p><p>In this comprehensive guide, I’ll take you from dispatcher basics to advanced optimization techniques, with <strong>real configuration examples</strong> you can use in production.</p><h3>Table of Contents</h3><ol><li>What is AEM Dispatcher?</li><li>Architecture &amp; How It Works</li><li>Installation &amp; Setup</li><li>Configuration Deep Dive</li><li>Caching Strategies</li><li>Security Hardening</li><li>Performance Optimization</li><li>Troubleshooting Common Issues</li><li>Real-World Scenarios</li><li>Best Practices Checklist</li></ol><h3>Part 1: What is AEM Dispatcher?</h3><p>The <strong>AEM Dispatcher</strong> is a caching and load-balancing tool that sits between your web server (Apache/IIS) and AEM publish instances. Think of it as a bouncer at a nightclub — it decides who gets in, who gets served from the VIP section (cache), and who needs to wait in line (fetch from AEM).</p><h3>Key Functions</h3><ol><li><strong>Caching</strong> — Stores rendered HTML pages to reduce load on AEM</li><li><strong>Load Balancing</strong> — Distributes requests across multiple publish instances</li><li><strong>Security</strong> — Filters malicious requests and protects AEM</li><li><strong>SSL Termination</strong> — Handles HTTPS encryption</li><li><strong>URL Rewriting</strong> — Transforms URLs for SEO and routing</li></ol><h3>Why You Need It</h3><p><strong>Without Dispatcher:</strong></p><ul><li>Every request hits AEM directly</li><li>Publish instances get overwhelmed</li><li>Response times: 500–2000ms</li><li>Server costs: 💰💰💰</li></ul><p><strong>With Dispatcher:</strong></p><ul><li>90%+ of requests served from cache</li><li>Response times: 10–50ms</li><li>Reduced infrastructure costs</li><li>Better user experience</li></ul><h3>Part 2: Architecture &amp; How It Works</h3><h3>The Big Picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*Giz4ydH8rIpQxogJQe2noA.png" /></figure><pre>Internet Users<br>     ↓<br>Load Balancer (CDN)<br>     ↓<br>Web Server (Apache/IIS) + Dispatcher Module<br>     ↓<br>   Cache?<br>   ├─ YES → Serve from cache (fast!)<br>   └─ NO → Forward to AEM Publish<br>         ↓<br>    Cache Response<br>         ↓<br>    Serve to User</pre><h3>Request Flow: Step by Step</h3><p>Let&#39;s trace a request for www.example.com/products/laptop.html:</p><p><strong>Step 1: Request Arrives</strong></p><pre>GET /products/laptop.html HTTP/1.1<br>Host: www.example.com<br>User-Agent: Mozilla/5.0...</pre><p><strong>Step 2: Dispatcher Checks Rules</strong></p><ul><li>Is this URL allowed? (Check /filter rules)</li><li>Should it be cached? (Check /cache rules)</li><li>Which render farm to use? (Check /renders)</li></ul><p><strong>Step 3: Cache Lookup</strong></p><pre>Cache Directory: /var/www/html/cache/<br>Looking for: /var/www/html/cache/products/laptop.html</pre><p><strong>Step 4a: Cache HIT ✅</strong></p><ul><li>File exists and is fresh</li><li>Serve immediately (10-50ms)</li><li>No AEM involved</li></ul><p><strong>Step 4b: Cache MISS ❌</strong></p><ul><li>File doesn&#39;t exist or expired</li><li>Forward request to AEM publish</li><li>AEM renders the page (200-500ms)</li><li>Dispatcher caches the response</li><li>Serve to user</li></ul><p><strong>Step 5: Cache Invalidation</strong> When content is published in AEM:</p><ul><li>Flush agent sends invalidation request</li><li>Dispatcher deletes affected cache files</li><li>Next request rebuilds cache</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*_vHT50ts1PQa4jeWufQ3JA.png" /></figure><h3>Part 3: Installation &amp; Setup (Hands-On)</h3><h3>Prerequisites</h3><ul><li>Apache HTTP Server 2.4+ or IIS 8.5+</li><li>AEM 6.5+ running</li><li>Root/admin access to web server</li><li>Basic Linux/Windows knowledge</li></ul><h3>Installation on Apache (Linux)</h3><p><strong>Step 1: Download Dispatcher Module</strong></p><pre># Download from Adobe Package Share<br>cd /tmp<br>wget https://download.macromedia.com/dispatcher/download/dispatcher-apache2.4-linux-x86_64-4.3.6.tar.gz</pre><pre># Extract<br>tar -xvzf dispatcher-apache2.4-linux-x86_64-4.3.6.tar.gz</pre><p><strong>Step 2: Install Module</strong></p><pre># Copy module to Apache modules directory<br>sudo cp dispatcher-apache2.4-4.3.6.so /usr/lib64/httpd/modules/mod_dispatcher.so</pre><pre># Set permissions<br>sudo chmod 755 /usr/lib64/httpd/modules/mod_dispatcher.so</pre><p><strong>Step 3: Create Directory Structure</strong></p><pre># Create cache directory<br>sudo mkdir -p /var/www/html/cache<br>sudo chown apache:apache /var/www/html/cache</pre><pre># Create dispatcher config directory<br>sudo mkdir -p /etc/httpd/conf.dispatcher.d<br>sudo mkdir -p /etc/httpd/conf.dispatcher.d/cache<br>sudo mkdir -p /etc/httpd/conf.dispatcher.d/filters<br>sudo mkdir -p /etc/httpd/conf.dispatcher.d/renders<br>sudo mkdir -p /etc/httpd/conf.dispatcher.d/virtualhosts</pre><p><strong>Step 4: Verify Installation</strong></p><pre># Test Apache configuration<br>sudo apachectl configtest</pre><pre># Start/Restart Apache<br>sudo systemctl restart httpd</pre><pre># Check dispatcher module is loaded<br>sudo apachectl -M | grep dispatcher<br># Should output: dispatcher_module (shared)</pre><h3>Part 4: Configuration Deep Dive</h3><h3>Main Configuration File: dispatcher.any</h3><p>This is the heart of Dispatcher. Located at /etc/httpd/conf.dispatcher.d/dispatcher.any:</p><pre>/name &quot;publish-farm&quot;<br>/clientheaders<br>  {<br>  &quot;*&quot;<br>  }<br>  <br>/virtualhosts<br>  {<br>  &quot;www.example.com&quot;<br>  &quot;example.com&quot;<br>  }<br>  <br>/renders<br>  {<br>  /rend01<br>    {<br>    /hostname &quot;localhost&quot;<br>    /port &quot;4503&quot;<br>    /timeout &quot;0&quot;<br>    }<br>  /rend02<br>    {<br>    /hostname &quot;localhost&quot;<br>    /port &quot;4504&quot;<br>    /timeout &quot;0&quot;<br>    }<br>  }<br>  <br>/filter<br>  {<br>  # Deny everything by default<br>  /0001 { /type &quot;deny&quot; /glob &quot;*&quot; }<br>  <br>  # Allow access to content<br>  /0023 { /type &quot;allow&quot; /glob &quot;* /content/*&quot; }<br>  <br>  # Enable specific extensions<br>  /0041 { /type &quot;allow&quot; /glob &quot;* *.html&quot; }<br>  /0042 { /type &quot;allow&quot; /glob &quot;* *.json&quot; }<br>  /0043 { /type &quot;allow&quot; /glob &quot;* *.css&quot; }<br>  /0044 { /type &quot;allow&quot; /glob &quot;* *.js&quot; }<br>  /0045 { /type &quot;allow&quot; /glob &quot;* *.png&quot; }<br>  /0046 { /type &quot;allow&quot; /glob &quot;* *.jpg&quot; }<br>  /0047 { /type &quot;allow&quot; /glob &quot;* *.gif&quot; }<br>  <br>  # Block access to system areas<br>  /0062 { /type &quot;deny&quot; /glob &quot;* /system/*&quot; }<br>  /0063 { /type &quot;deny&quot; /glob &quot;* /apps/*&quot; }<br>  /0064 { /type &quot;deny&quot; /glob &quot;* /libs/*&quot; }<br>  <br>  # Block selectors<br>  /0081 { /type &quot;deny&quot; /glob &quot;* *.infinity.json&quot; }<br>  /0082 { /type &quot;deny&quot; /glob &quot;* *.tidy.json&quot; }<br>  /0083 { /type &quot;deny&quot; /glob &quot;* *.sysview.xml&quot; }<br>  /0084 { /type &quot;deny&quot; /glob &quot;* *.docview.json&quot; }<br>  /0085 { /type &quot;deny&quot; /glob &quot;* *.docview.xml&quot; }<br>  /0086 { /type &quot;deny&quot; /glob &quot;* *.*[0-9].json&quot; }<br>  <br>  # Block WCM requests<br>  /0087 { /type &quot;deny&quot; /glob &quot;* *.query.json*&quot; }<br>  }<br>  <br>/cache<br>  {<br>  /docroot &quot;/var/www/html/cache&quot;<br>  <br>  /statfileslevel &quot;2&quot;<br>  <br>  /allowAuthorized &quot;0&quot;<br>  <br>  /rules<br>    {<br>    /0000<br>      {<br>      /glob &quot;*&quot;<br>      /type &quot;allow&quot;<br>      }<br>    }<br>    <br>  /invalidate<br>    {<br>    /0000<br>      {<br>      /glob &quot;*&quot;<br>      /type &quot;deny&quot;<br>      }<br>    /0001<br>      {<br>      /glob &quot;*.html&quot;<br>      /type &quot;allow&quot;<br>      }<br>    /0002<br>      {<br>      /glob &quot;/content/*&quot;<br>      /type &quot;allow&quot;<br>      }<br>    }<br>    <br>  /allowedClients<br>    {<br>    /0000<br>      {<br>      /glob &quot;*&quot;<br>      /type &quot;deny&quot;<br>      }<br>    /0001<br>      {<br>      /glob &quot;127.0.0.1&quot;<br>      /type &quot;allow&quot;<br>      }<br>    /0002<br>      {<br>      /glob &quot;10.0.0.0/8&quot;<br>      /type &quot;allow&quot;<br>      }<br>    }<br>    <br>  /ignoreUrlParams<br>    {<br>    /0001 { /glob &quot;*&quot; /type &quot;deny&quot; }<br>    /0002 { /glob &quot;utm_*&quot; /type &quot;allow&quot; }<br>    /0003 { /glob &quot;gclid&quot; /type &quot;allow&quot; }<br>    /0004 { /glob &quot;fbclid&quot; /type &quot;allow&quot; }<br>    }<br>    <br>  /headers<br>    {<br>    &quot;Cache-Control&quot;<br>    &quot;Content-Disposition&quot;<br>    &quot;Content-Type&quot;<br>    &quot;Expires&quot;<br>    &quot;Last-Modified&quot;<br>    &quot;X-Content-Type-Options&quot;<br>    }<br>    <br>  /gracePeriod &quot;2&quot;<br>  <br>  /enableTTL &quot;1&quot;<br>  }<br>  <br>/statistics<br>  {<br>  /categories<br>    {<br>    /html { /glob &quot;*.html&quot; }<br>    /others { /glob &quot;*&quot; }<br>    }<br>  }</pre><h3>Understanding Each Section</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*Yp4AiPqGVAY5nw5HiX87yg.png" /></figure><h4>1. /clientheaders - Headers to Forward</h4><p>Controls which HTTP headers are passed from client to AEM:</p><pre>/clientheaders<br>  {<br>  &quot;*&quot;  # Forward all headers (use with caution)<br>  }</pre><pre># OR be specific (recommended):<br>/clientheaders<br>  {<br>  &quot;Host&quot;<br>  &quot;User-Agent&quot;<br>  &quot;Accept&quot;<br>  &quot;Accept-Language&quot;<br>  &quot;Authorization&quot;<br>  &quot;Referer&quot;<br>  }</pre><p><strong>Best Practice:</strong> Only forward necessary headers to improve cache efficiency.</p><h4>1. /clientheaders - Headers to Forward</h4><p>Controls which HTTP headers are passed from client to AEM:</p><pre>/clientheaders<br>  {<br>  &quot;*&quot;  # Forward all headers (use with caution)<br>  }</pre><pre># OR be specific (recommended):<br>/clientheaders<br>  {<br>  &quot;Host&quot;<br>  &quot;User-Agent&quot;<br>  &quot;Accept&quot;<br>  &quot;Accept-Language&quot;<br>  &quot;Authorization&quot;<br>  &quot;Referer&quot;<br>  }</pre><p><strong>Best Practice:</strong> Only forward necessary headers to improve cache efficiency.</p><h4>2. /virtualhosts - Domain Mapping</h4><p>Lists which domains this farm handles:</p><pre>/virtualhosts<br>  {<br>  &quot;www.example.com&quot;<br>  &quot;example.com&quot;<br>  &quot;m.example.com&quot;<br>  }</pre><h4>3. /renders - AEM Publish Instances</h4><p>Defines backend AEM servers:</p><pre>/renders<br>  {<br>  /rend01<br>    {<br>    /hostname &quot;aem-publish-1.internal.com&quot;<br>    /port &quot;4503&quot;<br>    /timeout &quot;10000&quot;  # 10 seconds<br>    /receiveTimeout &quot;300000&quot;  # 5 minutes for long requests<br>    /ipv4 &quot;1&quot;  # Force IPv4<br>    /secure &quot;0&quot;  # Use HTTP (HTTPS between dispatcher and AEM if &quot;1&quot;)<br>    }<br>  /rend02<br>    {<br>    /hostname &quot;aem-publish-2.internal.com&quot;<br>    /port &quot;4503&quot;<br>    /timeout &quot;10000&quot;<br>    }<br>  }</pre><p><strong>Load Balancing:</strong> Dispatcher uses round-robin by default. Requests distribute evenly across renders.</p><h4>4. /filter - Security Rules</h4><p>The most critical section for security:</p><pre># Rule format:<br># /XXXX { /type &quot;allow|deny&quot; /glob &quot;PATTERN&quot; }</pre><pre># Default deny all<br>/0001 { /type &quot;deny&quot; /glob &quot;*&quot; }</pre><pre># Allow specific paths<br>/0010 { /type &quot;allow&quot; /glob &quot;GET /content/*&quot; }<br>/0011 { /type &quot;allow&quot; /glob &quot;GET /etc.clientlibs/*&quot; }</pre><pre># Block dangerous selectors<br>/0050 { /type &quot;deny&quot; /glob &quot;* *.infinity.json*&quot; }<br>/0051 { /type &quot;deny&quot; /glob &quot;* *.tidy.json*&quot; }<br>/0052 { /type &quot;deny&quot; /glob &quot;* *.sysview.xml*&quot; }<br>/0053 { /type &quot;deny&quot; /glob &quot;* *.docview.*&quot; }<br>/0054 { /type &quot;deny&quot; /glob &quot;* *.*[0-9].json*&quot; }</pre><pre># Block query builder<br>/0060 { /type &quot;deny&quot; /glob &quot;* *.query.json*&quot; }<br>/0061 { /type &quot;deny&quot; /glob &quot;* /bin/querybuilder.json*&quot; }</pre><pre># Block WCM components<br>/0070 { /type &quot;deny&quot; /glob &quot;* /content/*.wcm.*&quot; }</pre><p><strong>Testing Filters:</strong></p><pre># Test if URL is allowed<br>curl -H &quot;X-Forwarded-For: 127.0.0.1&quot; http://localhost/content/example/en.html</pre><pre># Should be blocked<br>curl <a href="http://localhost/content/example/en.infinity.json">http://localhost/content/example/en.infinity.json</a><br># Expected: 404 Not Found</pre><h4>5. /cache - Caching Configuration</h4><p>The magic of Dispatcher happens here:</p><p><strong>Key Settings:</strong></p><pre>/cache<br>  {<br>  # Where to store cached files<br>  /docroot &quot;/var/www/html/cache&quot;<br>  <br>  # Stat files level (impacts invalidation)<br>  # 0 = single .stat file at docroot<br>  # 2 = .stat files at /content and /content/site level<br>  /statfileslevel &quot;2&quot;<br>  <br>  # Cache authenticated requests?<br>  # 0 = no (recommended)<br>  # 1 = yes (risky)<br>  /allowAuthorized &quot;0&quot;<br>  <br>  # Serve stale content while revalidating<br>  # 2 = serve stale for 2 seconds while fetching fresh<br>  /gracePeriod &quot;2&quot;<br>  <br>  # Enable Time-To-Live caching<br>  # 1 = respect Cache-Control headers<br>  /enableTTL &quot;1&quot;<br>  }</pre><p><strong>Caching Rules (</strong><strong>/rules):</strong></p><pre>/rules<br>  {<br>  # Cache everything by default<br>  /0000 { /glob &quot;*&quot; /type &quot;allow&quot; }<br>  <br>  # Don&#39;t cache query strings (unless whitelisted)<br>  /0001 { /glob &quot;*?*&quot; /type &quot;deny&quot; }<br>  <br>  # Don&#39;t cache POST requests<br>  /0002 { /glob &quot;POST *&quot; /type &quot;deny&quot; }<br>  <br>  # Cache specific patterns<br>  /0010 { /glob &quot;*.html&quot; /type &quot;allow&quot; }<br>  /0011 { /glob &quot;*.json&quot; /type &quot;allow&quot; }<br>  /0012 { /glob &quot;*.css&quot; /type &quot;allow&quot; }<br>  /0013 { /glob &quot;*.js&quot; /type &quot;allow&quot; }<br>  }</pre><p><strong>Invalidation Rules (</strong><strong>/invalidate):</strong></p><pre>/invalidate<br>  {<br>  # Default deny<br>  /0000 { /glob &quot;*&quot; /type &quot;deny&quot; }<br>  <br>  # Allow invalidation from AEM<br>  /0001 { /glob &quot;*.html&quot; /type &quot;allow&quot; }<br>  /0002 { /glob &quot;/content/*&quot; /type &quot;allow&quot; }<br>  /0003 { /glob &quot;/etc/*&quot; /type &quot;allow&quot; }<br>  }</pre><p><strong>Allowed Clients (</strong><strong>/allowedClients):</strong></p><p>Only these IPs can send flush requests:</p><pre>/allowedClients<br>  {<br>  /0000 { /glob &quot;*&quot; /type &quot;deny&quot; }<br>  <br>  # AEM author<br>  /0001 { /glob &quot;10.0.1.100&quot; /type &quot;allow&quot; }<br>  <br>  # AEM publish instances<br>  /0002 { /glob &quot;10.0.2.*&quot; /type &quot;allow&quot; }<br>  }</pre><h3>Part 5: Caching Strategies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*bODpNWsfqY6h1NlTxKE-0A.png" /></figure><h3>How Dispatcher Caching Works</h3><p><strong>File System Cache:</strong></p><pre>/var/www/html/cache/<br>├── content/<br>│   ├── example/<br>│   │   ├── en/<br>│   │   │   ├── products/<br>│   │   │   │   └── laptop.html<br>│   │   │   ├── .stat<br>│   │   │   └── home.html<br>│   │   └── .stat<br>│   └── .stat<br>├── etc.clientlibs/<br>│   └── clientlibs/<br>│       └── site.min.css<br>└── .stat</pre><h3>The .stat File Mechanism</h3><p>The .stat file is key to cache invalidation:</p><pre># Check .stat file<br>ls -la /var/www/html/cache/content/example/.stat</pre><pre># Output:<br>-rw-r--r-- 1 apache apache 0 Jan 05 10:30 .stat</pre><p><strong>How it works:</strong></p><ol><li>When content is published, AEM sends flush request</li><li>Dispatcher updates .stat file timestamp</li><li>For subsequent requests, Dispatcher compares:</li></ol><ul><li>Cached file modification time</li><li>.stat file modification time</li></ul><ol><li>If .stat is newer → Cache MISS → Fetch from AEM</li><li>If cached file is newer → Cache HIT → Serve from cache</li></ol><p><strong>statfileslevel Impact:</strong></p><pre># statfileslevel &quot;0&quot; (single .stat at root)<br>/var/www/html/cache/.stat</pre><pre># When /content/site-a/en/page1.html is published<br># ALL cache is invalidated (including site-b)</pre><pre># statfileslevel &quot;2&quot; (stats at site level)<br>/var/www/html/cache/content/.stat<br>/var/www/html/cache/content/site-a/.stat<br>/var/www/html/cache/content/site-b/.stat</pre><pre># When /content/site-a/en/page1.html is published<br># Only /content/site-a/.stat is updated<br># site-b cache remains valid ✅</pre><p><strong>Best Practice:</strong> Use statfileslevel &quot;2&quot; for multi-site setups.</p><h3>Ignore URL Parameters</h3><p>Marketing often adds tracking parameters that break caching:</p><pre># These are the same page:<br>/products/laptop.html<br>/products/laptop.html?utm_source=email<br>/products/laptop.html?utm_source=email&amp;utm_campaign=summer</pre><p><strong>Solution:</strong></p><pre>/ignoreUrlParams<br>  {<br>  # By default, deny all params (don&#39;t cache)<br>  /0001 { /glob &quot;*&quot; /type &quot;deny&quot; }<br>  <br>  # Whitelist marketing params to ignore<br>  /0002 { /glob &quot;utm_source&quot; /type &quot;allow&quot; }<br>  /0003 { /glob &quot;utm_medium&quot; /type &quot;allow&quot; }<br>  /0004 { /glob &quot;utm_campaign&quot; /type &quot;allow&quot; }<br>  /0005 { /glob &quot;utm_content&quot; /type &quot;allow&quot; }<br>  /0006 { /glob &quot;utm_term&quot; /type &quot;allow&quot; }<br>  /0007 { /glob &quot;gclid&quot; /type &quot;allow&quot; }<br>  /0008 { /glob &quot;fbclid&quot; /type &quot;allow&quot; }<br>  }</pre><p>Now all three URLs above serve the same cached file!</p><h3>TTL-Based Caching</h3><p>Traditional dispatcher invalidates on publish. TTL caching expires based on time:</p><pre>/cache<br>  {<br>  /enableTTL &quot;1&quot;<br>  }</pre><p><strong>In AEM, set Cache-Control headers:</strong></p><pre>// In your Servlet or Filter<br>response.setHeader(&quot;Cache-Control&quot;, &quot;max-age=3600&quot;); // 1 hour</pre><p><strong>Use Cases:</strong></p><ul><li>API responses that change infrequently</li><li>Third-party data (weather, stock prices)</li><li>Static assets with versioning</li></ul><h3>Cache Warming</h3><p>Pre-populate cache after deployment:</p><pre>#!/bin/bash<br># cache-warmer.sh</pre><pre>URLS=(<br>  &quot;https://www.example.com/&quot;<br>  &quot;https://www.example.com/products&quot;<br>  &quot;https://www.example.com/about&quot;<br>  &quot;https://www.example.com/contact&quot;<br>)</pre><pre>for url in &quot;${URLS[@]}&quot;; do<br>  echo &quot;Warming: $url&quot;<br>  curl -s -o /dev/null &quot;$url&quot;<br>done</pre><pre>echo &quot;Cache warming complete!&quot;</pre><p><strong>Schedule with cron:</strong></p><pre># Run after each deployment<br>0 3 * * * /usr/local/bin/cache-warmer.sh</pre><h3>Part 6: Security Hardening</h3><h3>Common Attack Vectors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*6KYFwQ4CZgC3y_oUlQK7dA.png" /></figure><h4>1. Selector Injection</h4><p><strong>Attack:</strong></p><pre>/content/example/en.docview.json<br>/content/example/en.infinity.json<br>/content/example/en.tidy.json</pre><p><strong>Defense:</strong></p><pre>/filter<br>  {<br>  /0050 { /type &quot;deny&quot; /glob &quot;* *.infinity.json*&quot; }<br>  /0051 { /type &quot;deny&quot; /glob &quot;* *.tidy.json*&quot; }<br>  /0052 { /type &quot;deny&quot; /glob &quot;* *.sysview.xml*&quot; }<br>  /0053 { /type &quot;deny&quot; /glob &quot;* *.docview.*&quot; }<br>  /0054 { /type &quot;deny&quot; /glob &quot;* *.*[0-9].json*&quot; }<br>  }</pre><h4>2. Path Traversal</h4><p><strong>Attack:</strong></p><pre>/content/../libs/granite/core/content/login.html<br>/content/example/en/../../../system/console</pre><p><strong>Defense:</strong></p><pre># In Apache config<br>RewriteEngine On<br>RewriteCond %{REQUEST_URI} \.\. [NC,OR]<br>RewriteCond %{REQUEST_URI} /\. [NC]<br>RewriteRule .* - [F,L]</pre><h4>3. Query Builder Exploitation</h4><p><strong>Attack:</strong></p><pre>/bin/querybuilder.json?path=/content&amp;type=cq:Page&amp;p.limit=-1</pre><p><strong>Defense:</strong></p><pre>/filter<br>  {<br>  /0060 { /type &quot;deny&quot; /glob &quot;* /bin/querybuilder.json*&quot; }<br>  /0061 { /type &quot;deny&quot; /glob &quot;* *.query.json*&quot; }<br>  }</pre><h4>4. Bypassing Dispatcher</h4><p><strong>Attack:</strong></p><pre># Appending random selector<br>/content/example/en.hackattempt.html</pre><p><strong>Defense:</strong></p><pre>/filter<br>  {<br>  # Explicitly whitelist allowed selectors<br>  /0100 { /type &quot;deny&quot; /glob &quot;* *.*.*&quot; }<br>  /0101 { /type &quot;allow&quot; /glob &quot;* *.html&quot; }<br>  /0102 { /type &quot;allow&quot; /glob &quot;* *.json&quot; }<br>  }</pre><h3>Security Checklist</h3><pre>✅ Default deny in /filter<br>✅ Whitelist only necessary paths<br>✅ Block all selector exploits<br>✅ Restrict /bin, /system, /apps, /libs<br>✅ Limit invalidation to AEM IPs only<br>✅ Disable directory listing in Apache<br>✅ Set X-Frame-Options header<br>✅ Set X-Content-Type-Options header<br>✅ Implement rate limiting<br>✅ Enable HTTPS only<br>✅ Regular security audits</pre><h3>Part 7: Performance Optimization</h3><h3>Apache Tuning</h3><p><strong>Enable Compression:</strong></p><pre>&lt;IfModule mod_deflate.c&gt;<br>  AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css<br>  AddOutputFilterByType DEFLATE application/javascript application/json<br>  AddOutputFilterByType DEFLATE image/svg+xml<br>&lt;/IfModule&gt;</pre><p><strong>Enable Browser Caching:</strong></p><pre>&lt;IfModule mod_expires.c&gt;<br>  ExpiresActive On<br>  ExpiresByType text/html &quot;access plus 10 minutes&quot;<br>  ExpiresByType text/css &quot;access plus 1 year&quot;<br>  ExpiresByType application/javascript &quot;access plus 1 year&quot;<br>  ExpiresByType image/jpeg &quot;access plus 1 year&quot;<br>  ExpiresByType image/png &quot;access plus 1 year&quot;<br>  ExpiresByType image/svg+xml &quot;access plus 1 year&quot;<br>&lt;/IfModule&gt;</pre><p><strong>Tune Apache MPM:</strong></p><pre>&lt;IfModule mpm_prefork_module&gt;<br>  StartServers 5<br>  MinSpareServers 5<br>  MaxSpareServers 10<br>  MaxRequestWorkers 250<br>  MaxConnectionsPerChild 1000<br>&lt;/IfModule</pre><h3>Dispatcher Optimization</h3><p><strong>1. Increase Render Timeout for Heavy Pages:</strong></p><pre>/renders<br>  {<br>  /rend01<br>    {<br>    /hostname &quot;aem-publish.internal&quot;<br>    /port &quot;4503&quot;<br>    /timeout &quot;60000&quot;  # 60 seconds for complex pages<br>    }<br>  }</pre><p><strong>2. Enable Sticky Sessions:</strong></p><pre>/stickyConnectionsFor &quot;/content/example/secure&quot;</pre><p><strong>3. Optimize Header Forwarding:</strong></p><pre># Only forward essential headers<br>/clientheaders<br>  {<br>  &quot;Host&quot;<br>  &quot;Accept&quot;<br>  &quot;Accept-Language&quot;<br>  &quot;Authorization&quot;<br>  }</pre><h3>Monitoring &amp; Metrics</h3><p><strong>Enable Dispatcher Statistics:</strong></p><pre>/statistics<br>  {<br>  /categories<br>    {<br>    /html { /glob &quot;*.html&quot; }<br>    /css { /glob &quot;*.css&quot; }<br>    /js { /glob &quot;*.js&quot; }<br>    /images { /glob &quot;*.{jpg,png,gif}&quot; }<br>    /json { /glob &quot;*.json&quot; }<br>    }<br>  }</pre><p><strong>View Statistics:</strong></p><pre># Access dispatcher statistics<br>curl http://localhost/dispatcher/invalidate.cache</pre><p><strong>Log Analysis:</strong></p><pre># Find cache misses<br>grep &quot;Unable to get cached copy&quot; /var/log/httpd/dispatcher.log</pre><pre># Find slow requests<br>grep &quot;processing.*took.*ms&quot; /var/log/httpd/dispatcher.log | awk &#39;{print $NF}&#39; | sort -n | tail -20</pre><pre># Cache hit ratio<br>total=$(grep -c &quot;GET &quot; /var/log/httpd/access_log)<br>cached=$(grep -c &quot;X-Dispatcher: HIT&quot; /var/log/httpd/access_log)<br>ratio=$(echo &quot;scale=2; $cached / $total * 100&quot; | bc)<br>echo &quot;Cache hit ratio: $ratio%&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*mce5eSmtPIh6oFAbMiAuTw.png" /></figure><h3>Part 8: Troubleshooting Common Issues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*CVZaPRwwXgQo3OdOMrAzog.png" /></figure><h3>Issue 1: Pages Not Caching</h3><p><strong>Symptoms:</strong></p><ul><li>Every request hits AEM</li><li>Slow response times</li><li>No files in /cache directory</li></ul><p><strong>Debug Steps:</strong></p><pre># 1. Check if caching is enabled<br>grep &quot;/cache&quot; /etc/httpd/conf.dispatcher.d/dispatcher.any</pre><pre># 2. Check cache rules<br>grep -A 10 &quot;/rules&quot; /etc/httpd/conf.dispatcher.d/dispatcher.any</pre><pre># 3. Check docroot permissions<br>ls -ld /var/www/html/cache<br># Should be: drwxr-xr-x apache apache</pre><pre># 4. Enable debug logging<br># In dispatcher.any, set DispatcherLogLevel to 7 (Debug)</pre><pre># 5. Test a request<br>curl -v <a href="http://localhost/content/example/en.html">http://localhost/content/example/en.html</a></pre><pre># 6. Check response headers<br># Look for: X-Dispatcher: HIT or MISS</pre><p><strong>Common Causes:</strong></p><pre>❌ Authorization header present<br>   Fix: /allowAuthorized &quot;0&quot;</pre><pre>❌ Query parameters in URL<br>   Fix: Add to /ignoreUrlParams</pre><pre>❌ Wrong cache rules<br>   Fix: Verify /cache/rules section</pre><pre>❌ Cache-Control: no-cache from AEM<br>   Fix: Check AEM page properties</pre><pre>❌ POST request (not cacheable)<br>   Fix: Use GET for cacheable content</pre><h3>Issue 2: Cache Not Invalidating</h3><p><strong>Symptoms:</strong></p><ul><li>Old content showing after publish</li><li>Manual cache clear works</li><li>Flush agent firing but no effect</li></ul><p><strong>Debug Steps:</strong></p><p>bash</p><pre># 1. Check flush agent in AEM<br># Author &gt; Tools &gt; Deployment &gt; Replication &gt; Flush Agent</pre><pre># 2. Verify allowed clients<br>grep -A 10 &quot;/allowedClients&quot; /etc/httpd/conf.dispatcher.d/dispatcher.any</pre><pre># 3. Test manual invalidation<br>curl -X POST <a href="http://localhost/dispatcher/invalidate.cache">http://localhost/dispatcher/invalidate.cache</a></pre><pre># 4. Check .stat file updates<br>watch -n 1 &#39;ls -la /var/www/html/cache/content/.stat&#39;</pre><pre># 5. Verify invalidation rules<br>grep -A 10 &quot;/invalidate&quot; /etc/httpd/conf.dispatcher.d/dispatcher.any</pre><p><strong>Solution:</strong></p><pre># Ensure AEM IP is whitelisted<br>/allowedClients<br>  {<br>  /0001 { /glob &quot;10.0.1.100&quot; /type &quot;allow&quot; }  # AEM Author IP<br>  }</pre><pre># Verify flush agent configuration in AEM<br>Transport URI: <a href="http://dispatcher-server/dispatcher/invalidate.cache">http://dispatcher-server/dispatcher/invalidate.cache</a></pre><h3>Issue 3: 404 Errors</h3><p><strong>Symptoms:</strong></p><ul><li>Content exists in AEM</li><li>Returns 404 from Dispatcher</li><li>Works when accessing AEM directly</li></ul><p><strong>Debug:</strong></p><pre># 1. Check filter rules<br>curl -v http://localhost/content/example/en.html 2&gt;&amp;1 | grep &quot;&lt; HTTP&quot;</pre><pre># 2. Check Apache error log<br>tail -f /var/log/httpd/error_log</pre><pre># 3. Check dispatcher log<br>tail -f /var/log/httpd/dispatcher.log | grep &quot;denied&quot;</pre><pre># 4. Test filter bypass<br>curl -H &quot;X-Dispatcher-Bypass: true&quot; <a href="http://localhost/content/example/en.html">http://localhost/content/example/en.html</a></pre><p><strong>Solution:</strong></p><pre># Add rule to allow the path<br>/filter<br>  {<br>  /0100 { /type &quot;allow&quot; /glob &quot;GET /content/example/*&quot; }<br>  }</pre><h3>Issue 4: Performance Degradation</h3><p><strong>Symptoms:</strong></p><ul><li>Slow response times</li><li>High CPU usage</li><li>Apache MaxClients warnings</li></ul><p><strong>Debug:</strong></p><pre># 1. Check Apache status<br>curl http://localhost/server-status</pre><pre># 2. Monitor connections<br>netstat -an | grep :80 | wc -l</pre><pre># 3. Check cache hit ratio<br>grep -c &quot;X-Dispatcher: HIT&quot; /var/log/httpd/access_log</pre><pre># 4. Find slow endpoints<br>awk &#39;{print $7}&#39; /var/log/httpd/access_log | sort | uniq -c | sort -rn | head -20</pre><pre># 5. Check disk I/O<br>iostat -x 1</pre><p><strong>Solutions:</strong></p><p>apache</p><pre># Increase Apache limits<br>MaxRequestWorkers 500</pre><pre># Enable KeepAlive<br>KeepAlive On<br>KeepAliveTimeout 5<br>MaxKeepAliveRequests 100</pre><pre># Tune render timeout<br>/timeout &quot;30000&quot;</pre><pre># Add more publish instances<br>/renders { /rend01 { ... } /rend02 { ... } }</pre><h3>Part 9: Real-World Scenarios</h3><h3>Scenario 1: Multi-Site Setup</h3><p><strong>Challenge:</strong> 100+ sites on one AEM instance, each site should have isolated cache.</p><p><strong>Solution:</strong></p><pre># Use statfileslevel and separate virtualhosts</pre><pre>/farms<br>  {<br>  /site-a<br>    {<br>    /virtualhosts { &quot;site-a.com&quot; }<br>    /cache<br>      {<br>      /docroot &quot;/var/www/html/cache/site-a&quot;<br>      /statfileslevel &quot;2&quot;<br>      }<br>    }<br>    <br>  /site-b<br>    {<br>    /virtualhosts { &quot;site-b.com&quot; }<br>    /cache<br>      {<br>      /docroot &quot;/var/www/html/cache/site-b&quot;<br>      /statfileslevel &quot;2&quot;<br>      }<br>    }<br>  }</pre><h3>Scenario 2: Personalized Content</h3><p><strong>Challenge:</strong> Homepage shows personalized content, can’t cache entire page.</p><p><strong>Solution: Edge Side Includes (ESI)</strong></p><pre>&lt;!-- Cache wrapper page --&gt;<br>&lt;html&gt;<br>&lt;head&gt;...&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;!-- Static content (cached) --&gt;<br>  &lt;header&gt;...&lt;/header&gt;<br>  <br>  &lt;!-- Dynamic content (not cached) --&gt;<br>  &lt;esi:include src=&quot;/content/example/en/personalized.html&quot;/&gt;<br>  <br>  &lt;!-- Static content (cached) --&gt;<br>  &lt;footer&gt;...&lt;/footer&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Or use AJAX for personalization:</strong></p><pre>// Page loads from cache (fast)<br>// Then fetch personalized data<br>fetch(&#39;/bin/api/user/recommendations.json&#39;)<br>  .then(res =&gt; res.json())<br>  .then(data =&gt; renderPersonalization(data));</pre><h3>Scenario 3: High-Traffic Event</h3><p><strong>Challenge:</strong> Product launch, expecting 10x normal traffic.</p><p><strong>Pre-Launch Checklist:</strong></p><pre># 1. Warm cache for all critical pages<br>./cache-warmer.sh</pre><pre># 2. Increase Apache workers<br>MaxRequestWorkers 1000</pre><pre># 3. Add more publish instances<br># Scale from 2 to 6 publish servers</pre><pre># 4. Enable CDN (Cloudflare/Akamai)<br># Serve static assets from CDN</pre><pre># 5. Extend TTL for semi-static content<br>Cache-Control: max-age=1800  # 30 minutes</pre><pre># 6. Monitor in real-time<br>watch -n 5 &#39;curl -s <a href="http://localhost/server-status">http://localhost/server-status</a> | grep &quot;requests currently being processed&quot;&#39;</pre><h3>Scenario 4: Secure Member Area</h3><p><strong>Challenge:</strong> Members-only content, requires authentication.</p><p><strong>Solution:</strong></p><pre># DON&#39;T cache authenticated requests<br>/cache<br>  {<br>  /allowAuthorized &quot;0&quot;<br>  }</pre><pre># Use separate farm for secure content<br>/farms<br>  {<br>  /public<br>    {<br>    /cache { ... }<br>    /filter<br>      {<br>      /0001 { /type &quot;allow&quot; /glob &quot;* /content/public/*&quot; }<br>      }<br>    }<br>    <br>  /secure<br>    {<br>    /cache<br>      {<br>      /rules { /0001 { /glob &quot;*&quot; /type &quot;deny&quot; } }  # No caching<br>      }<br>    /filter<br>      {<br>      /0001 { /type &quot;allow&quot; /glob &quot;* /content/secure/*&quot; }<br>      }<br>    /sessionmanagement<br>      {<br>      /directory &quot;/tmp/dispatcher-sessions&quot;<br>      /timeout &quot;3600&quot;<br>      }<br>    }<br>  }</pre><h3>Part 10: Best Practices Checklist</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*2FjruQuq3joKKdnQU1Z1-g.png" /></figure><h3>Configuration</h3><ul><li>✅ Use environment-specific configs (dev, stage, prod)</li><li>✅ Set statfileslevel &quot;2&quot; for multi-site</li><li>✅ Implement granular filter rules</li><li>✅ Whitelist tracking parameters in ignoreUrlParams</li><li>✅ Enable TTL caching for appropriate content</li><li>✅ Configure proper timeout values</li><li>✅ Set up multiple render farms for redundancy</li></ul><h3>Security</h3><ul><li>✅ Default deny in /filter</li><li>✅ Block all selector exploits</li><li>✅ Restrict /allowedClients to AEM IPs only</li><li>✅ Enable HTTPS with strong ciphers</li><li>✅ Set security headers (X-Frame-Options, CSP)</li><li>✅ Regular security audits</li><li>✅ Keep Dispatcher module updated</li></ul><h3>Performance</h3><ul><li>✅ Tune Apache MPM settings</li><li>✅ Enable gzip compression</li><li>✅ Set proper cache headers</li><li>✅ Implement cache warming</li><li>✅ Monitor cache hit ratio (target &gt;90%)</li><li>✅ Use CDN for global distribution</li><li>✅ Optimize render farm count</li></ul><h3>Operations</h3><ul><li>✅ Centralized logging (ELK/Splunk)</li><li>✅ Automated deployments</li><li>✅ Health check endpoints</li><li>✅ Alerting for cache issues</li><li>✅ Regular log analysis</li><li>✅ Documented runbooks</li><li>✅ Disaster recovery plan</li></ul><h3>Configuration Files Reference</h3><h3>Complete Production-Ready Example</h3><p><strong>File Structure:</strong></p><pre>/etc/httpd/conf.dispatcher.d/<br>├── dispatcher.any                    # Main config<br>├── enabled_farms/<br>│   ├── 001_publish.any              # Public site farm<br>│   └── 002_secure.any               # Authenticated farm<br>├── cache/<br>│   ├── rules.any                    # Cache rules<br>│   └── invalidate.any               # Invalidation rules<br>├── filters/<br>│   ├── filters.any                  # Security filters<br>│   └── ams_publish_filters.any      # AMS recommended filters<br>├── renders/<br>│   └── renders.any                  # Publish instances<br>└── virtualhosts/<br>    └── virtualhosts.any             # Domain mappings</pre><p><strong>Download complete config:</strong></p><pre># Get Adobe&#39;s recommended baseline<br>git clone https://github.com/adobe/aem-project-archetype<br>cd aem-project-archetype/src/main/archetype/dispatcher.cloud</pre><h3>Tools &amp; Resources</h3><h3>Useful Commands</h3><pre># Test dispatcher config<br>/usr/sbin/dispatcher -t -f /etc/httpd/conf.dispatcher.d/dispatcher.any</pre><pre># Reload config without downtime<br>apachectl graceful</pre><pre># View real-time requests<br>tail -f /var/log/httpd/access_log | grep --line-buffered &quot;GET&quot; | cut -d&#39; &#39; -f7</pre><pre># Clear entire cache<br>rm -rf /var/www/html/cache/*</pre><pre># Clear specific site cache<br>find /var/www/html/cache/content/example -type f -delete</pre><pre># Check cache size<br>du -sh /var/www/html/cache/</pre><pre># Monitor cache writes<br>watch -n 1 &#39;find /var/www/html/cache -type f -mmin -1 | wc -l&#39;</pre><h3>Testing Tools</h3><pre># Siege - Load testing<br>siege -c 100 -t 60s https://www.example.com/</pre><pre># Apache Bench<br>ab -n 1000 -c 10 <a href="https://www.example.com/">https://www.example.com/</a></pre><pre># Check cache headers<br>curl -I <a href="https://www.example.com/content/example/en.html">https://www.example.com/content/example/en.html</a></pre><pre># Test with different user agents<br>curl -A &quot;Mobile&quot; <a href="https://www.example.com/">https://www.example.com/</a></pre><h3>Conclusion</h3><p>The AEM Dispatcher is a powerful tool that dramatically improves performance and security. By following the practices in this guide, you can:</p><ul><li><strong>Achieve 90%+ cache hit rates</strong></li><li><strong>Reduce response times from seconds to milliseconds</strong></li><li><strong>Handle 10x more traffic with the same infrastructure</strong></li><li><strong>Secure your AEM instance from common attacks</strong></li></ul><h3>Key Takeaways</h3><ol><li><strong>Start with security</strong> — Default deny, whitelist specific patterns</li><li><strong>Understand caching mechanics</strong> — .stat files, invalidation, TTL</li><li><strong>Monitor continuously</strong> — Cache ratio, response times, errors</li><li><strong>Tune for your use case</strong> — Multi-site vs single-site, public vs authenticated</li><li><strong>Test thoroughly</strong> — Load test before production deployment</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a666a04ace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Content Fragments: From Architecture to Headless Implementation with React]]></title>
            <link>https://medium.com/@prashantx7979/understanding-content-fragments-from-architecture-to-headless-implementation-with-react-48c747e7577d?source=rss-91a262276cf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/48c747e7577d</guid>
            <category><![CDATA[aem-content-fragment]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[headless-cms]]></category>
            <dc:creator><![CDATA[Prashant Kumar]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 04:13:36 GMT</pubDate>
            <atom:updated>2026-01-12T04:13:36.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Question Every AEM Developer Asks</h3><p>After mastering Experience Fragments, I faced a new challenge:</p><blockquote><strong><em>Content Fragments seem similar to Experience Fragments — both are reusable content. But Content Fragments are completely different! They’re stored differently, used differently, and work with headless architectures. How do Content Fragments actually work? How do they integrate with React for headless CMS? What’s the complete architecture?</em></strong></blockquote><p>When I explored Content Fragments, I discovered:</p><pre>Experience Fragments: Visual component blocks (HTML/CSS)<br>Content Fragments: Structured pure data (JSON)</pre><pre>But how does this &quot;pure data&quot; become a website or app?</pre><p>This article explains the complete Content Fragment architecture, implementation, and headless integration with React.</p><h3>Table of Contents</h3><ol><li>Understanding Content Fragments vs Experience Fragments</li><li>Content Fragment Architecture Deep Dive</li><li>Content Fragment Models: The Schema Foundation</li><li>Creating and Managing Content Fragments</li><li>Querying Content Fragments with GraphQL</li><li>Headless Architecture: How It All Works</li><li>React Integration: Building a Headless App</li><li>Real-World Implementation: Building a Blog</li><li>Best Practices and Performance Optimization</li><li>Advanced Patterns and Use Cases</li></ol><h3>1. Understanding Content Fragments vs Experience Fragments</h3><p>Let’s start by clearing up the confusion between these two similar-sounding but fundamentally different features.</p><h3>The Fundamental Difference:</h3><p><strong>Experience Fragments:</strong></p><ul><li><strong>What:</strong> Visual component blocks with presentation</li><li><strong>Contains:</strong> HTML, CSS, JavaScript, images</li><li><strong>Purpose:</strong> Reusable UI components (headers, footers, CTAs)</li><li><strong>Rendering:</strong> Server-side, includes styling</li><li><strong>Usage:</strong> Traditional web pages</li><li><strong>Output:</strong> Rendered HTML</li></ul><p><strong>Content Fragments:</strong></p><ul><li><strong>What:</strong> Structured pure data without presentation</li><li><strong>Contains:</strong> Text, numbers, dates, references (no HTML/CSS)</li><li><strong>Purpose:</strong> Content as data, channel-agnostic</li><li><strong>Rendering:</strong> Client-side or via GraphQL</li><li><strong>Usage:</strong> Headless CMS, multi-channel delivery</li><li><strong>Output:</strong> JSON or XML data</li></ul><h3>Visual Comparison:</h3><p><strong>Experience Fragment Example:</strong></p><pre>&lt;!-- XF contains presentation --&gt;<br>&lt;header class=&quot;site-header&quot; style=&quot;...&quot;&gt;<br>    &lt;img src=&quot;/logo.png&quot; class=&quot;logo&quot;/&gt;<br>    &lt;nav class=&quot;navigation&quot;&gt;<br>        &lt;ul&gt;<br>            &lt;li&gt;&lt;a href=&quot;/home&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/nav&gt;<br>&lt;/header&gt;</pre><p><strong>Content Fragment Example:</strong></p><pre>// CF contains only data<br>{<br>  &quot;title&quot;: &quot;Understanding AEM&quot;,<br>  &quot;author&quot;: &quot;John Doe&quot;,<br>  &quot;publishDate&quot;: &quot;2025-01-15&quot;,<br>  &quot;category&quot;: &quot;Technology&quot;,<br>  &quot;content&quot;: &quot;AEM is a powerful CMS...&quot;,<br>  &quot;tags&quot;: [&quot;AEM&quot;, &quot;CMS&quot;, &quot;Adobe&quot;]<br>}</pre><h3>The Key Insight:</h3><blockquote><strong><em>Experience Fragments = Content + Presentation</em></strong></blockquote><blockquote><strong><em>Content Fragments = Content Only (Presentation-Free)</em></strong></blockquote><p>This makes Content Fragments perfect for:</p><ul><li>✅ Headless CMS architectures</li><li>✅ Multi-channel delivery (web, mobile, IoT)</li><li>✅ APIs and microservices</li><li>✅ Content reuse across different presentations</li><li>✅ Structured, queryable content</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M89YRotPIpjJRaJLNbKc4w.png" /></figure><h3>2. Content Fragment Architecture Deep Dive</h3><p>Now let’s understand how Content Fragments are architected in AEM.</p><h3>The Three-Layer Architecture:</h3><p><strong>Layer 1: Content Fragment Models (Schema)</strong></p><pre>Path: /conf/your-project/settings/dam/cfm/models/<br>Purpose: Define structure and data types<br>Think of it as: Database table schema or TypeScript interface</pre><p><strong>Layer 2: Content Fragments (Data)</strong></p><pre>Path: /content/dam/your-project/content-fragments/<br>Purpose: Actual content instances based on models<br>Think of it as: Database records or JSON documents</pre><p><strong>Layer 3: Delivery Layer (APIs)</strong></p><pre>Endpoints: <br>- GraphQL API: /content/graphql/endpoint.gql<br>- REST API: /api/assets/content-fragment-path<br>- Content Services: /content/site/page.model.json</pre><pre>Purpose: Expose content as consumable data<br>Think of it as: REST API or GraphQL endpoint</pre><h3>Storage Structure in CRXDE:</h3><p><strong>Content Fragment Model:</strong></p><pre>/conf/healthportal/settings/dam/cfm/models/<br>└─ article/<br>    └─ jcr:content/<br>        ├─ cq:model (defines the model)<br>        └─ model/<br>            ├─ title (Single-line text)<br>            ├─ author (Single-line text)<br>            ├─ publishDate (Date &amp; Time)<br>            ├─ category (Tags)<br>            ├─ content (Multi-line text)<br>            ├─ excerpt (Multi-line text)<br>            ├─ featuredImage (Content Reference)<br>            └─ relatedArticles (Multiple Content References)</pre><p><strong>Content Fragment Instance:</strong></p><pre>/content/dam/healthportal/articles/<br>└─ understanding-aem/<br>    └─ jcr:content/<br>        ├─ cq:model = &quot;/conf/healthportal/settings/dam/cfm/models/article&quot;<br>        └─ data/<br>            ├─ master/ (master variation)<br>            │   ├─ title = &quot;Understanding AEM Architecture&quot;<br>            │   ├─ author = &quot;John Doe&quot;<br>            │   ├─ publishDate = &quot;2025-01-15T10:00:00.000Z&quot;<br>            │   ├─ category = [&quot;Technology&quot;, &quot;AEM&quot;]<br>            │   ├─ content = &quot;AEM is a powerful enterprise CMS...&quot;<br>            │   ├─ excerpt = &quot;Learn about AEM&#39;s core architecture...&quot;<br>            │   ├─ featuredImage = &quot;/content/dam/images/aem-hero.jpg&quot;<br>            │   └─ relatedArticles = [<br>            │         &quot;/content/dam/articles/aem-basics&quot;,<br>            │         &quot;/content/dam/articles/sling-overview&quot;<br>            │       ]<br>            └─ mobile/ (mobile variation - optional)<br>                ├─ title = &quot;Understanding AEM&quot; (shorter)<br>                └─ content = &quot;Condensed version...&quot;</pre><h3>Key Architectural Components:</h3><p><strong>1. Content Fragment Model (CFM)</strong></p><ul><li>Defines data structure (fields, types, validation)</li><li>Similar to database schema</li><li>Reusable across multiple fragments</li><li>Located in /conf/ hierarchy</li></ul><p><strong>2. Content Fragment</strong></p><ul><li>Instance of a model with actual data</li><li>Stored as DAM asset in /content/dam/</li><li>Can have multiple variations (master, mobile, etc.)</li><li>Versionable and translatable</li></ul><p><strong>3. Variations</strong></p><ul><li>Different versions of the same content</li><li>Master variation (default)</li><li>Custom variations (mobile, social, etc.)</li><li>Each variation can have different field values</li></ul><p><strong>4. GraphQL Schema</strong></p><ul><li>Auto-generated from Content Fragment Models</li><li>Provides type-safe queries</li><li>Enables complex queries with filters</li><li>Introspectable schema</li></ul><h3>How They Connect:</h3><pre>Content Fragment Model (Schema)<br>    ↓ defines structure<br>Content Fragment (Data Instance)<br>    ↓ exposed via<br>GraphQL Schema (Auto-generated)<br>    ↓ queried by<br>Client Application (React, Mobile, etc.)<br>    ↓ renders<br>User Interface</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgTlDh2G1xqyVvZZu8zV7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lA0J08Ta8ub6yNjDTM1wcg.png" /></figure><h3>The Storage Model:</h3><p>Unlike Experience Fragments (stored as cq:Page), Content Fragments are stored as:</p><pre>&lt;!-- Content Fragment is a DAM Asset --&gt;<br>&lt;jcr:root<br>    jcr:primaryType=&quot;dam:Asset&quot;<br>    jcr:mixinTypes=&quot;[dam:Taggable]&quot;&gt;<br>    <br>    &lt;jcr:content<br>        jcr:primaryType=&quot;dam:AssetContent&quot;<br>        cq:model=&quot;/conf/healthportal/settings/dam/cfm/models/article&quot;&gt;<br>        <br>        &lt;data jcr:primaryType=&quot;nt:unstructured&quot;&gt;<br>            &lt;master jcr:primaryType=&quot;nt:unstructured&quot;&gt;<br>                &lt;!-- Field values stored here --&gt;<br>            &lt;/master&gt;<br>        &lt;/data&gt;<br>        <br>        &lt;metadata jcr:primaryType=&quot;nt:unstructured&quot;&gt;<br>            &lt;!-- DAM metadata --&gt;<br>        &lt;/metadata&gt;<br>    &lt;/jcr:content&gt;<br>&lt;/jcr:root&gt;</pre><p><strong>Key Point:</strong> Content Fragments are DAM assets (dam:Asset), not pages! This is fundamentally different from Experience Fragments</p><h3>3. Content Fragment Models: The Schema Foundation</h3><p>Content Fragment Models are the blueprint that defines what data your Content Fragments can contain.</p><h3>What is a Content Fragment Model?</h3><p>Think of it like:</p><ul><li><strong>Database Schema:</strong> Defines tables and columns</li><li><strong>TypeScript Interface:</strong> Defines object structure</li><li><strong>JSON Schema:</strong> Validates JSON structure</li><li><strong>Class Definition:</strong> Defines properties and types</li></ul><h3>Creating a Content Fragment Model:</h3><p><strong>Step 1: Navigate to Models Console</strong></p><pre>Tools → Assets → Content Fragment Models</pre><p><strong>Step 2: Select Configuration</strong></p><pre>Select your project configuration: /conf/healthportal<br>(If not exists, create it first)</pre><p><strong>Step 3: Create Model</strong></p><pre>Click &quot;Create&quot; → Name: &quot;Article&quot;<br>Title: &quot;Blog Article&quot;</pre><p><strong>Step 4: Add Fields (Data Types)</strong></p><p>AEM provides various field types:</p><p><strong>Available Data Types:</strong></p><ol><li><strong>Single Line Text</strong></li></ol><ul><li>Simple text input</li><li>Example: Title, Author name</li><li>Max length validation available</li></ul><p><strong>2. Multi Line Text</strong></p><ul><li>Rich text or plain text</li><li>Example: Article content, Description</li><li>Can enable rich text formatting</li></ul><p><strong>3. Number</strong></p><ul><li>Integer or decimal</li><li>Example: Price, Rating, View count</li><li>Min/max validation available</li></ul><p><strong>4. Boolean</strong></p><ul><li>True/false checkbox</li><li>Example: Featured, Published, Premium</li></ul><p><strong>5. Date &amp; Time</strong></p><ul><li>Date picker with optional time</li><li>Example: Publish date, Event date</li><li>Can set default to current date</li></ul><p><strong>6. Enumeration</strong></p><ul><li>Dropdown or radio buttons</li><li>Example: Status (Draft/Review/Published)</li><li>Predefined options</li></ul><p><strong>7. Tags</strong></p><ul><li>AEM tag picker</li><li>Example: Categories, Keywords</li><li>Multiple selection allowed</li></ul><p><strong>9. Content Reference</strong></p><ul><li>Reference to another asset</li><li>Example: Featured image, Related content</li><li>Can restrict to specific paths</li></ul><p><strong>10. Fragment Reference</strong></p><ul><li>Reference to another Content Fragment</li><li>Example: Author profile, Related articles</li><li>Enables complex relationships</li></ul><p><strong>11. JSON Object</strong></p><ul><li>Structured JSON data</li><li>Example: Custom metadata</li><li>For advanced use cases</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrqfDI1L-5_NoueAU0Gs5Q.png" /></figure><h3>Model Configuration in CRXDE:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLSyzuicsrM_JSi3FuEUEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55c8_Y_IFkxMGAmwv2ZOTw.png" /></figure><h3>4. Creating and Managing Content Fragments</h3><p>Now that we have a model, let’s create Content Fragment instances.</p><h3>Creating a Content Fragment:</h3><p><strong>Method 1: Via Assets Console (UI)</strong></p><p><strong>Step 1: Navigate to DAM</strong></p><pre>Assets → Files → Navigate to /content/dam/healthportal/articles</pre><p><strong>Step 2: Create Fragment</strong></p><pre>Click &quot;Create&quot; → &quot;Content Fragment&quot;</pre><p><strong>Step 3: Select Model</strong></p><pre>Choose model: &quot;Blog Article&quot;<br>Title: &quot;Understanding AEM Architecture&quot;</pre><p><strong>Step 4: Fill in Content</strong></p><pre>Title: Understanding AEM Architecture<br>Author: John Doe<br>Publish Date: 2025-01-15<br>Category: Technology, AEM<br>Status: Published<br>Featured: Yes<br>Excerpt: Learn about the core architectural principles...<br>Content: [Rich text content here]<br>Featured Image: /content/dam/healthportal/images/aem-hero.jpg<br>SEO Title: AEM Architecture Guide | HealthPortal<br>SEO Description: Comprehensive guide to Adobe Experience Manager architecture<br>Related Articles: [Select 2-3 related articles]</pre><p><strong>Step 5: Save and Publish</strong></p><pre>Save → Publish</pre><h3>Structure of Created Fragment in CRXDE:</h3><pre>/content/dam/healthportal/articles/understanding-aem-architecture/<br>├─ jcr:content/<br>    ├─ jcr:primaryType = &quot;dam:AssetContent&quot;<br>    ├─ cq:model = &quot;/conf/healthportal/settings/dam/cfm/models/article&quot;<br>    ├─ contentFragment = true<br>    │<br>    ├─ data/<br>    │   └─ master/                    ← Master variation<br>    │       ├─ title = &quot;Understanding AEM Architecture&quot;<br>    │       ├─ author = &quot;John Doe&quot;<br>    │       ├─ publishDate = &quot;2025-01-15T10:00:00.000Z&quot;<br>    │       ├─ category = [&quot;healthportal:technology&quot;, &quot;healthportal:aem&quot;]<br>    │       ├─ status = &quot;published&quot;<br>    │       ├─ featured = true<br>    │       ├─ excerpt = &quot;Learn about the core architectural...&quot;<br>    │       ├─ content = &quot;&lt;p&gt;AEM is a powerful enterprise CMS...&lt;/p&gt;&quot;<br>    │       ├─ featuredImage = &quot;/content/dam/healthportal/images/aem-hero.jpg&quot;<br>    │       ├─ seoTitle = &quot;AEM Architecture Guide&quot;<br>    │       ├─ seoDescription = &quot;Comprehensive guide to...&quot;<br>    │       ├─ relatedArticles = [<br>    │       │     &quot;/content/dam/healthportal/articles/aem-basics&quot;,<br>    │       │     &quot;/content/dam/healthportal/articles/sling-intro&quot;<br>    │       │   ]<br>    │       ├─ viewCount = 1250<br>    │       └─ rating = 4.5<br>    │<br>    └─ metadata/<br>        ├─ dc:title = &quot;Understanding AEM Architecture&quot;<br>        ├─ dc:description = &quot;Learn about...&quot;<br>        ├─ dam:size = 45678<br>        ├─ dam:sha1 = &quot;abc123...&quot;<br>        └─ cq:tags = [&quot;healthportal:technology&quot;]</pre><h3>Managing Variations:</h3><p>Content Fragments support variations — different versions of the same content for different channels.</p><p><strong>Creating a Mobile Variation:</strong></p><pre>1. Open Content Fragment editor<br>2. Click &quot;Variations&quot; in left rail<br>3. Click &quot;Create Variation&quot;<br>4. Name: &quot;mobile&quot;<br>5. Title: &quot;Mobile Version&quot;<br>6. Based on: &quot;Master&quot;</pre><p><strong>Mobile Variation — Modified Fields:</strong></p><pre>mobile/<br>├─ title = &quot;Understanding AEM&quot; (shorter)<br>├─ excerpt = &quot;Core AEM architecture guide&quot; (condensed)<br>├─ content = &quot;&lt;p&gt;Brief version...&lt;/p&gt;&quot; (summarized)<br>└─ (other fields inherited from master)</pre><h3>Variation Use Cases:</h3><p><strong>Master Variation:</strong></p><ul><li>Default, most complete version</li><li>Used for web desktop</li></ul><p><strong>Mobile Variation:</strong></p><ul><li>Shorter titles</li><li>Condensed content</li><li>Optimized for small screens</li></ul><p><strong>Social Variation:</strong></p><ul><li>Social media optimized text</li><li>Different tone</li><li>Hashtags included</li></ul><p><strong>Email Variation:</strong></p><ul><li>Email-friendly formatting</li><li>Call-to-action focused</li><li>Shorter content</li></ul><h3>Content Fragment Metadata:</h3><p>Beyond the model fields, Content Fragments have standard DAM metadata:</p><pre>Metadata:<br>- Title<br>- Description<br>- Tags<br>- Creation date<br>- Modification date<br>- Created by<br>- Modified by<br>- Copyright<br>- License<br>- Expiry date</pre><h3>5. Querying Content Fragments with GraphQL</h3><p>This is where Content Fragments become powerful — exposing structured data via GraphQL API.</p><h3>GraphQL Basics:</h3><p><strong>What is GraphQL?</strong></p><ul><li>Query language for APIs</li><li>Client specifies exactly what data it needs</li><li>Single endpoint for all queries</li><li>Strongly typed schema</li><li>Efficient (no over-fetching or under-fetching)</li></ul><h3>AEM GraphQL Setup:</h3><p><strong>Step 1: Enable GraphQL Endpoint</strong></p><p>Navigate to:</p><pre>Tools → General → Configuration Browser<br>Select: healthportal<br>Enable: GraphQL Persisted Queries</pre><p>Create GraphQL Endpoint:</p><pre>Tools → Assets → GraphQL<br>Create → Endpoint<br>Name: healthportal-endpoint<br>Path: /content/cq:graphql/healthportal/endpoint</pre><p><strong>Step 2: GraphQL Schema Auto-Generation</strong></p><p>AEM automatically generates GraphQL schema from your Content Fragment Models!</p><p>graphql</p><pre># Auto-generated from &quot;article&quot; model</pre><pre>type Article {<br>  _path: String!<br>  title: String!<br>  author: String!<br>  authorProfile: AuthorProfileModel<br>  publishDate: DateTime!<br>  category: [String]<br>  status: String<br>  featured: Boolean<br>  excerpt: String!<br>  content: MultiFormatString!<br>  featuredImage: ContentReference<br>  seoTitle: String<br>  seoDescription: String<br>  relatedArticles: [ArticleModel]<br>  viewCount: Int<br>  rating: Float<br>  _variations: [String]<br>}</pre><pre>type ArticleModel implements ContentFragment {<br>  _path: String!<br>  _model: ContentFragmentModel<br>  _variation(variation: String): Article<br>  master: Article<br>  mobile: Article<br>}</pre><h3>Basic GraphQL Queries:</h3><p><strong>Query 1: Get Single Article</strong></p><pre>query GetArticle {<br>  articleByPath(_path: &quot;/content/dam/healthportal/articles/understanding-aem-architecture&quot;) {<br>    item {<br>      _path<br>      title<br>      author<br>      publishDate<br>      excerpt<br>      content {<br>        html<br>        plaintext<br>      }<br>      featuredImage {<br>        ... on ImageRef {<br>          _path<br>          _authorUrl<br>          _publishUrl<br>          mimeType<br>          width<br>          height<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>Response:</strong></p><pre>{<br>  &quot;data&quot;: {<br>    &quot;articleByPath&quot;: {<br>      &quot;item&quot;: {<br>        &quot;_path&quot;: &quot;/content/dam/healthportal/articles/understanding-aem-architecture&quot;,<br>        &quot;title&quot;: &quot;Understanding AEM Architecture&quot;,<br>        &quot;author&quot;: &quot;John Doe&quot;,<br>        &quot;publishDate&quot;: &quot;2025-01-15T10:00:00.000Z&quot;,<br>        &quot;excerpt&quot;: &quot;Learn about the core architectural principles...&quot;,<br>        &quot;content&quot;: {<br>          &quot;html&quot;: &quot;&lt;p&gt;AEM is a powerful enterprise CMS...&lt;/p&gt;&quot;,<br>          &quot;plaintext&quot;: &quot;AEM is a powerful enterprise CMS...&quot;<br>        },<br>        &quot;featuredImage&quot;: {<br>          &quot;_path&quot;: &quot;/content/dam/healthportal/images/aem-hero.jpg&quot;,<br>          &quot;_authorUrl&quot;: &quot;http://localhost:4502/content/dam/healthportal/images/aem-hero.jpg&quot;,<br>          &quot;_publishUrl&quot;: &quot;https://healthportal.com/content/dam/healthportal/images/aem-hero.jpg&quot;,<br>          &quot;mimeType&quot;: &quot;image/jpeg&quot;,<br>          &quot;width&quot;: 1920,<br>          &quot;height&quot;: 1080<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>Persisted Queries:</h3><p>For production, use <strong>persisted queries</strong> (cached and optimized):</p><p><strong>Create Persisted Query:</strong></p><pre>POST /graphql/persist.json/healthportal/getFeaturedArticles</pre><pre>Body:<br>query getFeaturedArticles {<br>  articleList(<br>    filter: {<br>      featured: { _expressions: [{ value: true }] }<br>    }<br>    sort: &quot;publishDate DESC&quot;<br>    limit: 5<br>  ) {<br>    items {<br>      _path<br>      title<br>      author<br>      excerpt<br>    }<br>  }<br>}</pre><p><strong>Execute Persisted Query:</strong></p><pre>GET /graphql/execute.json/healthportal/getFeaturedArticles</pre><h3>GraphQL Endpoint URLs:</h3><p><strong>Author Instance:</strong></p><pre>http://localhost:4502/content/graphql/healthportal/endpoint.gql</pre><p><strong>Publish Instance:</strong></p><pre>https://your-site.com/content/graphql/healthportal/endpoint.gql</pre><p><strong>Persisted Queries:</strong></p><pre>https://your-site.com/graphql/execute.json/healthportal/queryName</pre><h3>6. Headless Architecture: How It All Works</h3><p>Now let’s understand how Content Fragments enable headless CMS architecture.</p><h3>What is Headless CMS?</h3><p><strong>Traditional (Coupled) CMS:</strong></p><pre>Content → Templates → Rendered HTML → Browser<br>(Content and presentation tightly coupled)</pre><p><strong>Headless CMS:</strong></p><pre>Content → API (JSON/GraphQL) → Any Client → Any Device<br>(Content and presentation decoupled)</pre><h3>The Headless Architecture Stack:</h3><p><strong>Backend (AEM):</strong></p><pre>┌─────────────────────────────────────┐<br>│   Content Fragment Models           │<br>│   (Define structure)                │<br>└─────────────────────────────────────┘<br>            ↓<br>┌─────────────────────────────────────┐<br>│   Content Fragments                 │<br>│   (Store data)                      │<br>└─────────────────────────────────────┘<br>            ↓<br>┌─────────────────────────────────────┐<br>│   GraphQL API / REST API            │<br>│   (Expose data)                     │<br>└─────────────────────────────────────┘<br>            ↓<br>         JSON</pre><p><strong>Frontend (React/Vue/Angular/Mobile):</strong></p><pre>JSON<br>            ↓<br>┌─────────────────────────────────────┐<br>│   Client Application                │<br>│   (Fetch data via API)              │<br>└─────────────────────────────────────┘<br>            ↓<br>┌─────────────────────────────────────┐<br>│   Components                        │<br>│   (Render UI)                       │<br>└─────────────────────────────────────┘<br>            ↓<br>┌─────────────────────────────────────┐<br>│   User Interface                    │<br>│   (Web, Mobile, IoT, etc.)          │<br>└─────────────────────────────────────┘</pre><h3>Complete Headless Flow:</h3><p><strong>Step 1: Author Creates Content</strong></p><pre>Content Author in AEM:<br>1. Opens Content Fragment editor<br>2. Creates new &quot;Article&quot; fragment<br>3. Fills in all fields (title, content, etc.)<br>4. Saves and publishes</pre><p><strong>Step 2: Content Stored in AEM</strong></p><pre>Content Fragment saved to:<br>/content/dam/healthportal/articles/new-article</pre><pre>Data structure:<br>{<br>  &quot;title&quot;: &quot;10 Health Tips&quot;,<br>  &quot;author&quot;: &quot;Dr. Smith&quot;,<br>  &quot;content&quot;: &quot;Here are 10 essential health tips...&quot;,<br>  &quot;publishDate&quot;: &quot;2025-01-15&quot;,<br>  ...<br>}</pre><p><strong>Step 3: GraphQL Schema Updated</strong></p><pre>AEM automatically exposes the fragment via GraphQL:<br>Type: ArticleModel<br>Available at: /content/graphql/healthportal/endpoint.gql</pre><p><strong>Step 4: Client Queries API</strong></p><pre>// React app makes GraphQL request<br>const query = `<br>  query GetArticles {<br>    articleList {<br>      items {<br>        title<br>        author<br>        excerpt<br>        featuredImage {<br>          _publishUrl<br>        }<br>      }<br>    }<br>  }<br>`;<br>fetch(&#39;https://your-aem.com/content/graphql/healthportal/endpoint.gql&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({ query })<br>})<br>.then(res =&gt; res.json())<br>.then(data =&gt; {<br>  // Render articles in React components<br>});</pre><p><strong>Step 5: Client Renders UI</strong></p><pre>// React component renders the data<br>function ArticleList({ articles }) {<br>  return (<br>    &lt;div className=&quot;article-grid&quot;&gt;<br>      {articles.map(article =&gt; (<br>        &lt;ArticleCard<br>          key={article._path}<br>          title={article.title}<br>          author={article.author}<br>          excerpt={article.excerpt}<br>          image={article.featuredImage._publishUrl}<br>        /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Multi-Channel Delivery:</h3><p>The same Content Fragment can be consumed by multiple channels:</p><p><strong>Web Application (React):</strong></p><pre>// Desktop web app<br>fetch(&#39;https://aem.com/graphql/endpoint.gql&#39;)<br>  .then(data =&gt; renderWebsite(data));</pre><p><strong>Mobile App (React Native):</strong></p><pre>// Mobile app<br>fetch(&#39;https://aem.com/graphql/endpoint.gql&#39;)<br>  .then(data =&gt; renderMobileApp(data));</pre><p><strong>Smart TV App:</strong></p><pre>// TV interface<br>fetch(&#39;https://aem.com/graphql/endpoint.gql&#39;)<br>  .then(data =&gt; renderTVInterface(data));</pre><h3>Benefits of Headless with Content Fragments:</h3><p>✅ <strong>Omnichannel Delivery</strong> — One content source, many outputs</p><p>✅ <strong>Technology Freedom</strong> — Use any frontend framework</p><p>✅ <strong>Performance</strong> — Client-side rendering, CDN caching</p><p>✅ <strong>Scalability</strong> — Separate scaling of backend and frontend</p><p>✅ <strong>Developer Experience</strong> — Modern development tools</p><p>✅ <strong>Future-Proof</strong> — Easy to add new channels</p><p>✅ <strong>Personalization</strong> — Client-side personalization easier</p><h3>Conclusion</h3><p>Congratulations! You’ve now mastered Content Fragments — from basic concepts to advanced headless implementations.</p><h3>What You’ve Learned:</h3><p>✅ <strong>Content Fragments vs Experience Fragments</strong> — Understanding the fundamental difference</p><p>✅ <strong>Architecture Deep Dive</strong> — Three-layer model (Models, Fragments, APIs)</p><p>✅ <strong>Content Fragment Models</strong> — Creating schemas with all data types</p><p>✅ <strong>Creating &amp; Managing Fragments</strong> — Practical implementation steps</p><p>✅ <strong>GraphQL Queries</strong> — From basic to advanced querying patterns</p><p>✅ <strong>Headless Architecture</strong> — How it enables omnichannel delivery</p><p>✅ <strong>React Integration</strong> — Building a complete headless application</p><p>✅ <strong>Real-World Blog</strong> — Implementing a production-ready system</p><p>✅ <strong>Best Practices</strong> — Performance optimization and common pitfalls</p><p>✅ <strong>Advanced Patterns</strong> — Multi-language, A/B testing, PWA, SSR</p><h3>The Power of Content Fragments:</h3><p>Content Fragments transform AEM into a <strong>true headless CMS</strong>, enabling:</p><p>🌐 <strong>Omnichannel Delivery</strong> — Web, mobile, IoT, voice — one content source ⚡ <strong>Performance</strong> — Client-side rendering, CDN caching, optimized delivery 🚀 <strong>Developer Experience</strong> — Modern frameworks (React, Vue, Angular) 📊 <strong>Structured Data</strong> — Type-safe, queryable, validated content 🔄 <strong>Content Reuse</strong> — Write once, use everywhere 🌍 <strong>Global Scale</strong> — Multi-language, multi-region support 🎯 <strong>Personalization</strong> — Dynamic content based on user profiles</p><h3>Key Takeaways:</h3><p><strong>1. Content as Data</strong></p><pre>Traditional CMS: Content = HTML<br>Headless CMS: Content = Structured Data (JSON)</pre><pre>This separation enables true omnichannel delivery</pre><p><strong>2. Model-First Approach</strong></p><pre>Always start with Content Fragment Models<br>Think about structure before creating content<br>Models = Contract between content and code</pre><p><strong>3. GraphQL is Your Friend</strong></p><pre>Type-safe queries<br>Request only what you need<br>Auto-generated from models<br>Single endpoint for all data</pre><p><strong>4. Think Beyond Web</strong></p><pre>Today: Website<br>Tomorrow: Mobile app, Smart TV, Voice assistant<br>Plan for multi-channel from day one</pre><p><strong>5. Performance Matters</strong></p><pre>Use persisted queries<br>Implement caching strategically<br>Lazy load images<br>Code split components<br>Monitor and optimize</pre><h3>From Theory to Production:</h3><p>You can now:</p><ol><li><strong>Design Content Models</strong> — Create scalable, reusable schemas</li><li><strong>Build Headless Apps</strong> — Implement React/Vue/Angular apps</li><li><strong>Optimize Performance</strong> — Apply caching, pagination, lazy loading</li><li><strong>Deploy at Scale</strong> — Multi-language, multi-region architectures</li><li><strong>Debug Issues</strong> — Understand the complete data flow</li></ol><h3>The Headless Future:</h3><p>Content Fragments position you for:</p><ul><li>📱 <strong>Mobile-First</strong> — Native app experiences</li><li>🎙️ <strong>Voice-First</strong> — Alexa, Google Assistant integration</li><li>🚗 <strong>IoT</strong> — Smart devices, automotive displays</li><li>🥽 <strong>AR/VR</strong> — Immersive experiences</li><li>🤖 <strong>AI-Powered</strong> — Machine learning on structured data</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48c747e7577d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>