<?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 Ediz NAJIM on Medium]]></title>
        <description><![CDATA[Stories by Ediz NAJIM on Medium]]></description>
        <link>https://medium.com/@ediznajim?source=rss-660c8f63dea9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NCfPxyhARi3x0oZj2lj1qA.png</url>
            <title>Stories by Ediz NAJIM on Medium</title>
            <link>https://medium.com/@ediznajim?source=rss-660c8f63dea9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:07:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ediznajim/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[2030: The End of Coding or the Beginning of a Different Kind of Engineer?]]></title>
            <link>https://medium.com/@ediznajim/2030-the-end-of-coding-or-the-beginning-of-a-different-kind-of-engineer-1d8aa6f45f4d?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d8aa6f45f4d</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[staai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 21:14:47 GMT</pubDate>
            <atom:updated>2026-08-11T21:14:47.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjEHf7ODTM6gRTDGLYQOwg.png" /></figure><p>The World Economic Forum expects major economic and technological changes to create around 170 million jobs and displace 92 million by 2030. Looking specifically at AI and information processing technologies, it estimates roughly 11 million jobs created and 9 million displaced.</p><p>The ILO reaches a similar conclusion from another direction. Around one in four jobs worldwide has some exposure to Generative AI, but exposure does not mean disappearance. In most cases, the work itself is more likely to change.</p><p>That distinction matters when we talk about software engineering.</p><p>I do not expect software developers simply to disappear. What I do expect is that a growing part of the work we have traditionally called coding will be automated. As that happens, more of an developer’s value moves toward design, requirements, architecture, verification, integration, security, and judgment.</p><p><em>AI may not eliminate the profession. It may change what the profession spends its time doing.</em></p><p>For most of my career, writing code was one of the defining skills of a software developer.</p><p>You learned a programming language. Then another. You learned frameworks, databases, testing, design patterns, debugging, deployment, distributed systems, and eventually architecture.</p><p>Experience accumulated slowly. You became better partly because you wrote thousands of lines of code, introduced bugs, fixed them, misunderstood requirements, inherited bad systems, rewrote poor designs, watched production fail, and gradually developed judgment.</p><p>Then AI changed the software development lifecycle.</p><p><em>Today, I can describe a feature and receive a reasonable implementation in seconds.</em></p><p>AI can generate an API, write SQL, create tests, refactor a class, explain unfamiliar code, migrate between frameworks, review a pull request, investigate logs, suggest infrastructure, or propose a fix for an error that might previously have taken an developer an afternoon.</p><p><em>And this is probably one of the least capable versions of AI-assisted software development we will ever use.</em></p><p>The interesting question is therefore no longer: Will AI write code? It already does !</p><p>The more important question is: What happens to software engineering when writing code is no longer the scarce part?</p><p>If AI can generate implementations quickly, the bottleneck begins to move.</p><p>The difficult part is no longer only producing the code. It is deciding what should be built, defining the right boundaries and constraints, giving the system the right context, verifying what was generated, and taking responsibility for the result.</p><p>In other words, as implementation becomes easier, software architecture and engineering judgment become more important, not less.</p><p>That is why I do not think software engineering disappears. But I also do not think the future is simply today’s developer or architect using a better autocomplete tool.</p><p>The work itself is changing.</p><p>The unit of engineering work is shifting from writing implementations to directing and governing how implementations are produced.</p><p>The engineer of the past spent much of their time creating software directly. The engineer of the future may spend more time specifying intent, defining constraints, designing boundaries, directing AI systems, verifying their output, and deciding what they are allowed to do.</p><p>Once that changes, the profession changes with it. Some kinds of work become less valuable. New responsibilities and roles emerge. Junior developers may need a different path to build experience. Senior developers may be responsible for supervising not only systems, but also the AI agents changing those systems.</p><p>And the skills we need to stay relevant begin to change as well.</p><h3>The First Things to Disappear May Be Tasks Disguised as Jobs</h3><p>Predictions about AI and employment usually become unnecessarily dramatic. One side says software engineers will disappear; the other says nothing important will change. Both positions miss the more immediate transformation.</p><p>The first things to disappear may not be entire professions. They may be tasks disguised as jobs.</p><p>Consider how much software work has historically followed the same pattern: a ticket arrives, the requirements are reasonably clear, and a developer turns them into code. Create an endpoint, add a few fields, write a database query, connect a page to an API, generate unit tests, map one object to another, add validation, upgrade a dependency, convert an implementation from one framework to another, fix a straightforward bug, or generate a report.</p><p>As AI becomes better at that transformation, the economic value of doing it manually begins to fall. That does not mean developers stop writing code. They will still inspect it, modify it, debug it, and write critical parts themselves. But they are likely to spend less of their time translating already understood intent into syntax.</p><p>The next generation of developers will need to spend more time on the work that comes before and around implementation: designing the software, defining functional requirements, defining non-functional requirements such as reliability, security, scalability, and performance, identifying constraints, clarifying assumptions, deciding where responsibilities belong, and determining how the system should behave when reality does not follow the expected path.</p><p>In that sense, AI does not remove software engineering; it changes where developers create value. The emphasis moves away from producing every implementation manually and toward the parts of the discipline that require more judgment, deeper technical understanding, and a broader view of the system.</p><p>This creates an uncomfortable but important distinction: Coding may remain essential knowledge while becoming a less valuable activity.</p><p>There is nothing contradictory about that. Calculators did not make mathematics irrelevant. Compilers did not make understanding computers irrelevant. Cloud platforms did not make infrastructure irrelevant. In each case, automation reduced the value of some lower-level work while increasing the importance of understanding what sat above it.</p><p><em>AI may do the same to programming.</em></p><h3>Code Is Becoming Abundant</h3><p>If AI reduces the amount of human effort required to implement software, the next consequence is obvious: organizations will be able to produce far more code than before.</p><p>For most of software history, code was expensive because producing it required significant human time. A new application, service, integration, migration, internal tool, or test suite had to be designed and implemented by developers. That effort naturally limited how much software an organization could create at once.</p><p>AI changes that constraint. When a developer can describe a change and have much of the implementation, testing, and documentation generated automatically, the cost of producing another piece of software begins to fall.</p><p>That sounds entirely positive, and in many ways it is. But it also creates a different problem.</p><p>The challenge may soon stop being that organizations cannot produce enough code. It may become that they can produce more code than they can properly understand, review, coordinate, and maintain.</p><p>Imagine a team where dozens — or eventually hundreds — of AI-generated changes can be proposed in a short period of time. Each change may look reasonable on its own. The code compiles. Tests pass. Documentation is generated. The agent can even explain why its solution makes sense.</p><p>The difficult question is no longer simply: Can we implement this?</p><p>It becomes: Should this change exist, does it fit with everything else, and can we trust what it changes in the system?</p><p>This is where the bottleneck moves.</p><p>When implementation is expensive, engineering capacity limits how much software can be produced. When implementation becomes cheap, the limiting factor becomes our ability to make good decisions about what is being produced.</p><p>AI therefore does not only accelerate implementation. It also accelerates the consequences of engineering decisions, good or bad.</p><p>Code becomes easier to generate. What becomes harder to scale is judgment, specification, verification, coordination, context, and responsibility.</p><h3>Specification Engineering May Matter More Than Prompt Engineering</h3><p>For the last few years, a lot of attention has gone into prompt engineering: how to ask the model the right question, how to structure instructions, and how to get a better response.</p><p>That is useful, but once AI starts writing real software, the harder problem moves somewhere else.</p><p>The problem is no longer only how we instruct the model. It is whether we have been precise enough about what the system is actually supposed to do.</p><p>Take something as simple as asking a coding agent to build a refund feature. The agent can generate the endpoint, database changes, validations, tests, and probably most of the surrounding code. But before it writes a single line, someone still has to define what a valid refund actually means.</p><p>Who can request one? How much can be refunded? Can the refunded amount exceed the original payment? Are partial refunds allowed? What happens if a refund has already been processed? Does a large refund require additional approval? What information must be recorded for audit purposes? What should happen when the business rules do not clearly cover a particular case?</p><p>Those questions are not implementation details. They define the behavior the implementation is supposed to preserve.</p><p>Once those rules are clear, AI can generate many possible implementations. Without them, it can still generate code, but we have no strong basis for deciding whether that code represents the system we actually wanted.</p><p>That is why specification becomes more important as code generation improves.</p><p><em>The specification may be much smaller than the implementation, but it contains more of the engineering judgment.</em></p><p>The software developer’s role therefore starts to move upstream. Instead of spending most of the effort explaining how to write the implementation, more effort goes into defining the intent, business rules, constraints, assumptions, and expected behavior before implementation begins.</p><p>What must always remain true? What must never happen? Which rules are mandatory? Which cases are exceptional? Which assumptions are we relying on? And what should happen when one of those assumptions no longer holds?</p><p>These questions existed long before AI. The difference is that when implementation becomes much faster, unclear thinking becomes much more expensive. A vague requirement can now turn into a large amount of plausible looking software very quickly.</p><p>As software becomes easier to produce, the scarce capability may increasingly be the ability to express what should be built, why it should behave that way, and under which constraints it is allowed to operate.</p><h3>What Changes When AI Produces More of the Implementation</h3><p>As AI generates more of the implementation, important rules cannot remain only in tickets, documents, diagrams, or people’s heads. Architecture rules, business constraints, security boundaries, and critical assumptions need to become clearer and, where possible, verifiable.</p><p>The system should be able to check what must remain true.</p><p>The same applies to authority. AI may be capable of doing something without being allowed to do it. A coding agent may modify code but not deploy it. A system may propose an action but still require approval.</p><p>Capability is what AI can do. Authority is what the system allows.</p><p>Verification also becomes more important. If AI can generate large amounts of code quickly, humans cannot simply review everything line by line. We need to know not only whether the code works, but whether it still respects the architecture, business rules, security boundaries, and assumptions of the system.</p><p>When generation scales, verification must scale too.</p><p>Testing changes as well. AI systems may behave differently even when the underlying code is correct, so we also need to evaluate outputs, tool choices, evidence, decisions, and overall behavior.</p><p>An AI system can pass its tests and still behave badly.</p><p>And debugging begins to change. The problem may not be a coding error at all. It may be bad context, a wrong assumption, a misleading tool description, or the wrong source of truth.</p><p>The question increasingly becomes: Why did this decision make sense to the system?</p><h3>New Engineering Roles Will Emerge</h3><p>If routine implementation becomes less valuable, other kinds of engineering work become more important.</p><p>Some of these may become new job titles. Others will simply become responsibilities added to existing roles. The exact names matter less than the shift in work.</p><p>Agentic Systems Architect Designs how models, tools, memory, workflows, policies, deterministic services, and humans fit together. The job is no longer only deciding which service calls which service, but also deciding what AI is allowed to decide, which actions remain deterministic, what context can be trusted, and where human control is required.</p><p>AI Evaluation Engineer Focuses on whether AI systems behave acceptably, not only whether the software technically works. This includes evaluating outputs, tool usage, agent behavior, regressions, model changes, and production quality.</p><p>Context Engineer Designs what information the AI receives and when. Retrieval, memory, freshness, provenance, tool descriptions, and context boundaries all become part of the system. A strong model with the wrong context can still make a bad decision.</p><p>AI Reliability Engineer Extends traditional reliability engineering into agentic behavior. Availability still matters, but so do tool loops, stale context, failed handoffs, partial execution, model degradation, unexpected behavior, and runaway cost.</p><p>AI Security and Control Engineer Focuses on risks that appear when AI can act: prompt injection, excessive permissions, data leakage, unsafe tool use, and weak approval boundaries.</p><p>AI Specification Engineer Turns business intent into clear rules, constraints, assumptions, and expected behavior before implementation begins. This responsibility may belong to architects, senior engineers, analysts, or technical product leaders rather than becoming a standalone title.</p><p>In that sense, some engineering roles will move from producing software directly to directing and controlling how software is produced.</p><h3>The Junior Engineer Problem</h3><p>There is another problem we should not ignore.</p><p>Most senior engineers became senior by doing exactly the kind of work AI is starting to automate: writing APIs, fixing bugs, maintaining legacy systems, creating tests, debugging incidents, and making plenty of mistakes along the way.</p><p>That work was not just implementation. It was how engineers built judgment.</p><p>So if more of those tasks are handled by AI, a difficult question appears:</p><p>How will junior engineers get the experience they need to become senior engineers?</p><p>The answer is probably not to force them to write boilerplate simply because previous generations did.</p><p>Instead, the way they learn may have to change. Juniors may spend less time producing routine code and more time reviewing AI-generated implementations, finding bad assumptions, challenging designs, testing failure cases, and understanding why a solution that looks correct may still be wrong.</p><p>That probably requires something many organizations do not yet have: a more deliberate engineering apprenticeship. If experience no longer accumulates naturally through thousands of routine implementation tasks, teams may need to create opportunities for juniors to investigate failures, review designs, reason about trade-offs, and defend technical decisions.</p><p>That could change not only how junior engineers work, but how we develop engineering judgment in the first place.</p><h3>What Should Software Engineers Learn Now?</h3><p>If the role is changing, the obvious question is what engineers should learn next.</p><p>The answer is not simply “learn AI,” and it is definitely not just prompt engineering. The important shift is learning how to build, evaluate, and control systems that include AI.</p><p>First, engineers need to understand how models behave: what context they receive, how they generate outputs, how tool calling works, where they fail, and what trade offs exist around cost, latency, and model choice. You do not need to become an AI researcher, but you do need to understand the component you are putting into your system.</p><p>The second area is context and agentic system design. That means learning how retrieval, memory, tools, workflows, permissions, human approval, and multi agent coordination fit together. A strong model with the wrong context or the wrong tools can still produce a bad system.</p><p>The third area is evaluation and verification. Traditional testing remains important, but it is not enough. Engineers need to know how to evaluate model outputs, tool choices, agent behavior, regressions, and failure cases, while also making sure generated software still respects architectural and business constraints.</p><p>Security changes too. Engineers need to understand risks such as prompt injection, excessive permissions, unsafe tool use, and data leakage. Once AI can act, security is no longer only about protecting code and infrastructure, it is also about controlling what the AI is allowed to do.</p><p>There is another skill that may become surprisingly important: communicating technical intent precisely.</p><p>Engineers will need to explain not only what they want an AI system to build, but why it should behave a certain way, which assumptions it can rely on, which constraints it must respect, and which trade-offs are acceptable.</p><p>This is not merely “prompt engineering.” It is a combination of technical writing, requirements analysis, architecture, and systems thinking. If AI is going to transform our intent into increasingly large amounts of software, ambiguity in that intent becomes an engineering problem.</p><p>A precise specification may eventually be as important as a precise implementation.</p><p>Programming still matters. Architecture still matters. Distributed systems, databases, security, and reliability still matter.</p><p>You still need to read generated code, debug it, challenge it, and understand what happens when it runs. The difference is that these skills are increasingly used to judge and control generated software, not only to write every part of it manually.</p><p>The future engineer needs both:</p><p>strong software engineering foundations and the ability to build and control AI-driven systems.</p><h3>The Engineering Flow Is Changing</h3><p>The traditional development flow was roughly:</p><p>Minimize image</p><p>Edit image</p><p>Delete image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*m59hlDmf-9FlvWJj" /></figure><p>As AI takes over more implementation work, the flow starts to look different:</p><p>Minimize image</p><p>Edit image</p><p>Delete image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*gptBvtEsStvnAjgD" /></figure><p>The important change is not the exact number of steps. It is where the human contribution moves.</p><p>More effort goes into defining what should be built, what rules must hold, what information the AI should receive, whether the generated result is correct, and what the system should be allowed to do.</p><p><em>Implementation is still part of engineering. It is simply becoming a smaller part of the whole.</em></p><h3>The Profession Is Moving From Production to Direction</h3><p>For years, a large part of a developer’s value came from producing the implementation: writing the class, the API, the query, the integration, the tests, and the deployment configuration.</p><p>That work will not disappear, but the center of gravity is moving.</p><p>The future engineer may create more value by deciding what should be built, defining the constraints, verifying machine-generated changes, coordinating AI agents, and understanding the consequences of what those systems produce.</p><p>This also changes who can participate in software creation. When implementation becomes easier, product managers, analysts, designers, and domain experts may be able to produce increasingly sophisticated software directly with AI.</p><p>That does not necessarily reduce the need for engineering. But it may change where engineering sits in the organization. The engineer becomes less of a translator between business intent and code and more of the person responsible for making sure that intent becomes a coherent, reliable system.</p><p><em>The profession is moving from producing software to directing, verifying, and governing how software is produced.</em></p><p>That is a much bigger change than simply writing code faster.</p><h3>Maybe 2030 Is Not the End of Coding</h3><p>I do not believe programmers disappear in 2030. But I do think the profession will change enough that simply being good at producing code will no longer be enough.</p><p>There will be people who become very good at using AI to generate software quickly. And there will be engineers who know how to make that software reliable, secure, coherent, observable, and safe. The second group will carry more responsibility because they are not only producing output. They are deciding whether that output belongs in the system at all.</p><p>AI may generate the implementation, write tests, review code, and eventually coordinate other agents. But someone still has to decide what the system should do, what it must never do, which information can be trusted, how much authority a machine should have, and when automation should stop.</p><p>Someone also has to communicate those decisions clearly enough that both humans and machines can act on them.</p><p>That is why I do not see AI as the end of software engineering. It may simply reduce the amount of time we spend producing code and increase the amount of time we spend understanding the consequences of what we build.</p><p>Perhaps 2030 will not be remembered as the end of coding. Perhaps it will be remembered as the moment we finally stopped confusing coding with engineering.</p><p>𝙏𝙚𝙘𝙝𝙣𝙤𝙡𝙤𝙜𝙮 𝙘𝙝𝙖𝙣𝙜𝙚𝙨. 𝙎𝙮𝙨𝙩𝙚𝙢𝙨 𝙏𝙝𝙞𝙣𝙠𝙞𝙣𝙜 𝙚𝙣𝙙𝙪𝙧𝙚𝙨. 𝐸𝒹𝒾𝓏 𝒩𝒶𝒿𝒾𝓂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d8aa6f45f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Systems Thinking for Agentic AI]]></title>
            <link>https://medium.com/softtechas/systems-thinking-for-agentic-ai-2ece5dbf061c?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ece5dbf061c</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 13:37:26 GMT</pubDate>
            <atom:updated>2026-08-04T11:35:51.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKRL-wCttFKvgLqxXHJSEA.png" /><figcaption>The LLM proposes. The system executes.</figcaption></figure><p>There is a point in almost every Agentic AI project when the conversation changes.</p><p>At first, the focus is capability.</p><p>Can the model understand the goal? Can it develop a plan? Can it select the right tool? Can it complete the task with limited human involvement?</p><p>Then the first serious failure occurs.</p><p>A tool times out after completing its operation, so the agent executes it again. A retrieved document appears highly relevant but contains a policy that expired two years earlier. A workflow stops halfway through, and nobody can determine which actions were committed. The model produces a valid instruction for the wrong customer account because the surrounding application trusted an identifier generated inside the prompt.</p><p>At that point, the central question is no longer:</p><p><strong><em>How capable is the model?</em></strong></p><p>It becomes:</p><p><strong><em>What kind of system did we build around it?</em></strong></p><p>This is where systems thinking becomes essential.</p><p>Agentic AI is often described as a language model connected to tools. In production, an agent is better understood as a control loop distributed across the model, application state, tools, policies and external services. The model provides probabilistic reasoning inside that loop, while the surrounding system controls execution.</p><p>The model matters, but so do state, permissions, information freshness, execution contracts, concurrency, retries, approval gates, observability, recovery and accountability.</p><p>A capable model inside a weak architecture does not create a reliable agent.</p><p><strong>It creates a more capable failure.</strong></p><h3>1. What Systems Thinking Means</h3><p>Systems thinking is a way of understanding outcomes by examining relationships, flows, constraints, delays and feedback across the entire system.</p><p>Systems thinking does not replace component-level analysis; it reveals where that analysis is insufficient.</p><p>A database, API, model, queue or service may behave correctly in isolation while the wider system still fails. The failure may emerge from the interaction between those components rather than from a defect in any one of them.</p><p>Consider a service that receives the same request twice and creates two financial transactions.</p><p>The immediate explanation may be that a retry caused the duplicate. That explanation is correct, but incomplete.</p><p>The retry occurred because the original response timed out. The timeout occurred because a downstream service was overloaded. The second request was accepted because the operation had no idempotency key. The duplicate remained undetected because monitoring captured technical errors but not repeated business effects. Recovery restarted the workflow from the beginning because completed steps had not been persisted.</p><p>No single component fully explains the incident.</p><p>The system produced the failure.</p><p>Systems thinking therefore asks a broader set of questions:<br>• What information moves through the system?<br>• Where does authoritative state live?<br>• Which component owns each state transition?<br>• What happens when an acknowledgement is delayed or lost?<br>• Which actions are reversible?<br>• Which failures amplify themselves through feedback?<br>• Where does execution authority begin and end?<br>• How is partial completion represented?<br>• Who remains accountable for the final outcome?</p><p>These questions have always mattered in software architecture.</p><p>Agentic AI makes them more urgent because probabilistic reasoning is now connected to stateful and potentially irreversible execution.</p><h3>2. Systems Thinking and Agentic AI</h3><p>Systems thinking and Agentic AI are closely connected because agent behaviour emerges from interaction.</p><p>The model contributes reasoning, while the system determines what that reasoning is allowed to become.</p><p>Three relationships are especially important.</p><h4>2.1 Reasoning and Control</h4><p>The model provides flexible interpretation and planning. The system provides deterministic validation, authority and execution. Without reasoning, automation becomes rigid. Without control, execution becomes unpredictable.</p><p>Production Agentic AI requires both, with a clear boundary between them.</p><h4>2.2 Autonomy and Constraint</h4><p>Autonomy becomes reliable only when it is bounded.</p><p>A narrow agent with a defined goal, limited tools, explicit permissions and clear stopping conditions is often more useful than a general agent with access to everything.</p><p>Constraint does not weaken autonomy. It gives autonomy a safe operating region.</p><h4>2.3 Local Decisions and System Wide Consequences</h4><p>The model typically chooses one next step.</p><p>The consequences may spread across many systems.</p><p>A retry affects load. A memory choice affects privacy. A stale document affects correctness. A tool permission affects security. A missing approval affects governance. A state-persistence failure affects recovery.</p><p>The model sees the immediate decision. The architecture must represent the wider consequences.</p><h3>3. Agentic AI Is a Control Loop</h3><p>A conventional LLM application often follows a short request-response path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoWmNqsyufkPq_Zc13laUQ.png" /><figcaption>Figure 1. Conventional LLM request-response flow. Original concept and content by Ediz Najim. Visual designed using Canva.</figcaption></figure><p>Agentic AI introduces a control loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTCIEO36F4qEIk8RakU8Ng.png" /><figcaption>Figure 2. The Agentic AI control loop: observe, reason, act and evaluate. Original concept and content by Ediz Najim. Visual designed using Canva.</figcaption></figure><p>The model participates in the decision stage, but the agent is the entire loop. Every iteration may change external state.</p><p>The agent may create a ticket, modify source code, reserve inventory, update a customer record, send a message, initiate a payment or trigger an infrastructure operation.</p><p>The model is no longer only generating language. It is influencing a system with durable consequences, and that changes the engineering problem.</p><p>A reliable agent cannot be evaluated solely by asking whether the model selected a reasonable next action. We also need to know:</p><p>• Was the observation complete and current?<br>• Was the proposed action valid for the current workflow state?<br>• Was the requester authorized to perform it?<br>• Were the tool arguments derived from authoritative data?<br>• Could the action be repeated safely?<br>• Was the resulting state persisted?<br>• Could another worker execute the same step concurrently?<br>• Can the workflow recover if the process crashes after the external side effect?<br>• Was human approval required before execution?<br>• Can the complete decision path be reconstructed later?<br>These are not prompt-engineering concerns.<br>They are architecture concerns.</p><h3>4. Workflow, Authority and Tool Boundaries</h3><p>An agent should not be allowed to act simply because the model suggests an action. The workflow defines what can happen next, the system decides whether the action is permitted, and tool boundaries control how the action is executed. This separation keeps the agent predictable, secure and easier to recover when something goes wrong.</p><h4>4.1 Model the Workflow as Explicit States</h4><p>An agentic workflow should not depend on the model remembering what happened earlier in the conversation.</p><p>The system should maintain an explicit record of the workflow’s current position: what has already happened, what is happening now, and what is allowed to happen next.</p><p>This can be represented as a set of states.</p><p>For example, a workflow may move through the following sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCCetSa5V8_Ty3rGhTegjA.png" /><figcaption>Figure 3. Explicit workflow states for controlled agent execution. Original concept and content by Ediz Najim. Visual designed using Canva.</figcaption></figure><p>Each state represents a confirmed fact about the workflow, not an assumption made by the model.</p><p><strong>CONTEXT_COLLECTED </strong>means that the required information has been retrieved and recorded.<br><strong>ACTION_PROPOSED</strong> means that the model has proposed an action, but the action has not yet been validated or authorized.<br><strong>ACTION_VALIDATED </strong>means that the proposal has passed the required business, security and policy checks.<br><strong>AWAITING_APPROVAL</strong> means that the action is valid but requires human authorization before execution.<br><strong>READY_TO_EXECUTE </strong>means that the action is valid and either requires no approval or has already received the required approval.<br><strong>ACTION_EXECUTED </strong>means that the external operation has completed successfully and its result has been recorded.</p><p>Failure and recovery states should be equally explicit:</p><p><strong>VALIDATION_FAILED</strong> means that the proposed action did not pass one or more required checks and cannot proceed.<br><strong>EXECUTION_FAILED </strong>means that the execution attempt failed and the system has confirmed that the intended operation was not completed.<br><strong>EXECUTION_UNCERTAIN</strong> means that the request may have reached the external system, but the system cannot yet confirm whether the side effect occurred.<br><strong>RECONCILIATION_PENDING</strong> means that authoritative records must be checked before the workflow can retry or continue.<br><strong>RETRY_PENDING</strong> means that another execution attempt has been approved or scheduled but has not yet started.<br><strong>RECOVERY_REQUIRED </strong>means that the normal workflow cannot continue and a recovery action, such as resuming, compensating or reconciling, is required.<br><strong>MANUAL_REVIEW</strong> means that the situation cannot be resolved safely through automated rules and requires human judgment.<br><strong>TERMINATED</strong> means that the workflow has been deliberately stopped and no further automated action is permitted.</p><p>The distinction between <strong>EXECUTION_FAILED</strong> and <strong>EXECUTION_UNCERTAIN </strong>is especially important. <strong>EXECUTION_FAILED </strong>confirms that the operation did not complete, while <strong>EXECUTION_UNCERTAIN </strong>requires reconciliation before any retry can be attempted safely.</p><p>These states prevent the workflow from becoming an informal sequence of messages whose operational meaning must be reconstructed later.</p><p>The model does not control these states directly.</p><p>The model may propose an action, but the application decides whether the workflow is allowed to move to the next state.</p><p>Consider an agent that proposes a fund transfer.</p><p>The presence of a transfer_funds tool call does not mean the transfer should be executed immediately. Before moving the workflow from <strong>ACTION_PROPOSED </strong>to <strong>ACTION_VALIDATED</strong>, the system must verify that:</p><p>• The account and transaction data are valid.<br>• The requester has the required permission.<br>• The supporting information is current.<br>• The transfer satisfies business and compliance rules.<br>• The action’s approval requirement has been identified.<br>• The execution limit has not been exceeded.<br>• The same logical transfer has not already been completed.<br>Only after these checks succeed can the system move the workflow into an executable state.</p><p>This creates a clear division of responsibility: the model proposes an action that may be useful, while the system determines whether it is valid, permitted and safe to execute.</p><p>By representing the workflow as explicit states, the application can prevent invalid actions, resume after failure, detect duplicate execution and explain exactly how the process reached its final outcome.</p><h4>4.2 Separate Reasoning from Authority</h4><p>The most important architectural principle in Agentic AI is the separation between reasoning and authority.</p><p>The model can interpret a goal, compare alternatives, summarize evidence and propose a next action.</p><p>It should not grant itself permission to execute that action.</p><p>A model may produce a structured proposal such as:</p><pre>{<br>  &quot;tool&quot;: &quot;suspend_customer_account&quot;,<br>  &quot;arguments&quot;: {<br>    &quot;customerId&quot;: &quot;C-18422&quot;,<br>    &quot;reason&quot;: &quot;Suspected fraud&quot;<br>  }<br>}</pre><p>If the application invokes the tool immediately, the model output has effectively become an execution command.</p><p>That is unsafe.</p><p>A structurally valid response may still be operationally wrong. The model may have selected the wrong customer, relied on stale evidence, misunderstood the business rule or repeated an action that already succeeded.</p><p>A proposal expresses what the model recommends. A command is the system-authorized instruction that may actually cross the execution boundary.</p><p>The system should convert a proposal into a controlled command only after deterministic checks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pj_QGvwifgpEgaYqrPWqBg.png" /><figcaption>Figure 4. Converting a model proposal into a validated and authorized execution command. Original concept and content by Ediz Najim. Visual designed using Canva.</figcaption></figure><p>The division of responsibility is clear:<br>The model proposes. The system validates and executes.<br>The human remains accountable for high exposure decisions.</p><h4>4.3 Tool Calling Is a Security and Consistency Boundary</h4><p>In many agent frameworks, a tool is represented by a name, a description and a JSON schema.</p><p>That representation helps the model select a tool, but it is not a complete execution contract.</p><p>A production tool is a security and consistency boundary between probabilistic reasoning and deterministic infrastructure.</p><p>Each tool should define:</p><p>• Authentication requirements<br>• Role-based or attribute-based authorization<br>• Allowed workflow states<br>• Input schema and semantic validation<br>• Output schema<br>• Side effects<br>• Timeout behaviour<br>• Retry classification<br>• Idempotency guarantees<br>• Rate limits<br>• Concurrency rules<br>• Data-access scope<br>• Audit requirements<br>• Compensation or reversal strategy</p><p>Consider a tool named update_customer_address.</p><p>A valid address does not automatically mean the operation is allowed. The system may still need to verify that the requester owns the customer relationship, the customer record is active, the data came from a trusted source, no conflicting update is in progress and the change does not require additional identity verification.</p><p>The tool description helps the model understand when the tool may be useful, while the implementation determines whether the operation is safe.</p><p>That distinction must never be delegated to the prompt.</p><h3>5. State Must Exist Outside the Prompt</h3><p>Many early agent implementations treat the context window as their primary state store.</p><p>This can work in prototypes because workflows are short, sessions remain active and failure scenarios are limited, but it breaks down quickly in production.</p><p>A prompt is not a durable workflow store. It does not provide transactional updates, concurrency control, structured querying, versioning or reliable recovery. It may be truncated, summarized or regenerated. It may represent what the model believed happened rather than what the infrastructure actually committed.</p><p>A production agent should persist several forms of state.</p><h4>5.1 Workflow State</h4><p>This records where the process currently stands:<br>• Current step<br>• Completed steps<br>• Pending steps<br>• Failure state<br>• Retry count<br>• Approval status<br>• Terminal outcome</p><h4>5.2 Execution State</h4><p>This records what happened at the tool boundary:<br>• Command identifier<br>• Tool name<br>• Input parameters<br>• Start and completion timestamps<br>• Execution status<br>• External reference<br>• Error category<br>• Idempotency key</p><h4>5.3 Evidence State</h4><p>This records the information that supported the decision:<br>• Retrieved document identifiers<br>• Source systems<br>• Document versions<br>• Effective dates<br>• Timestamps<br>• Policy versions<br>• Data lineage</p><h4>5.4 Decision State</h4><p>This records why the proposed action was accepted or rejected:<br>• Model version<br>• Prompt version<br>• Planner output<br>• Validation results<br>• Policy decisions<br>• Human approvals<br>• Retrieval scores, validation results, unresolved assumptions and explicit uncertainty indicators</p><p>These signals should come from observable checks where possible, not only from the model’s own estimate of confidence.</p><p>The model may receive a projection of this state, but it should never become the system of record.</p><h4>5.5 Operational State</h4><p>The current truth about the running workflow.</p><p>This is not optional memory. It is authoritative system state and must be persisted accordingly.</p><p>Confusing these categories creates dangerous designs.</p><p>A conversation summary may be acceptable as working memory.</p><p>It is not an acceptable source of truth for whether a payment completed.<br>Once information and operational state are separated clearly, the next question is which rules govern how that information may be used.</p><h3>6. Reliability and Recovery</h3><p>Agentic AI systems must continue working safely when errors, timeouts or partial failures occur. Reliability ensures that actions are executed consistently, while recovery allows the system to retry, resume from the last safe state or correct completed actions without losing control.</p><h4>6.1 Durable State Enables Recovery</h4><p>Suppose an agent must perform five operations:<br>• Load the customer record.<br>• Verify eligibility.<br>• Reserve inventory.<br>• Create an order.<br>• Send confirmation.</p><p>The first three steps succeed. The order API accepts the request, but the network connection closes before the response is received.</p><p>What should happen next?</p><p>A prompt-centred agent may interpret the timeout as failure and retry the order creation.</p><p>A system-centred agent asks a more precise question:</p><p>Did the command fail, or did the acknowledgement fail?</p><p>That distinction cannot be resolved reliably without durable execution state and idempotent command handling.</p><p>The application should persist an operation identifier before calling the external service. The receiving service should use that identifier to recognize repeated requests. Recovery should query the existing operation before deciding whether another attempt is required.</p><p>With durable state, an ambiguous failure becomes a controlled reconciliation problem.</p><p>The model should not be asked to infer infrastructure truth from a timeout message.</p><h4>6.2 Idempotency Is an Execution Contract</h4><p>Agentic workflows operate across unreliable boundaries.</p><p>A request may reach a service while its response is lost. A message may be delivered more than once. A worker may crash after committing a database update but before recording completion. A retry may be triggered by the platform, the application or the model.</p><p>Exactly-once execution is rarely something a distributed system can simply assume.</p><p>What production systems usually provide is closer to:</p><p>• At-least-once delivery<br>• Duplicate detection<br>• Idempotent processing<br>• Reconciliation after uncertainty</p><p>An idempotency key identifies one logical operation across repeated attempts.</p><p>For example:</p><pre>agentSessionId: A-401<br>workflowStep: CREATE_ORDER<br>businessEntity: CUSTOMER-991<br>logicalOperationId: A-401:CREATE_ORDER:CUSTOMER-991</pre><p>If the same operation is submitted again, the receiving service should return the original result or current status rather than create a second business effect.</p><p>Idempotency must be defined at the business-operation level.</p><p>Checking whether the HTTP request payload is identical is not enough. Two technically different requests may represent the same business intention, while two identical-looking requests may represent different intentions.</p><p>The business system must own that distinction.</p><p>The model may recommend another attempt, but it should not control retry execution. Whether, when and how an operation is retried must be defined by system policy and supported by idempotency and reconciliation.</p><h4>6.3 Concurrency Changes the Meaning of State</h4><p>Concurrency introduces another production concern.</p><p>What happens if two workers process the same agent session? What happens if a user modifies the underlying record while the agent is planning? What happens if two agents attempt conflicting actions on the same business entity?</p><p>Depending on the consistency requirements, this may involve:</p><p>• Optimistic locking<br>• Versioned state<br>• Compare-and-set updates<br>• Distributed locks<br>• Command deduplication<br>• Entity-level serialization<br>• Conflict detection<br>• Replanning after state changes</p><p>Suppose an agent reads account version 14 and proposes an action. Before execution, another process updates the account to version 15.</p><p>The original proposal may no longer be valid.</p><p>The execution layer should verify the expected version before committing the change. If the state has changed, the system should reject the command and return the updated state for replanning.</p><p>The model reasons over the version of state provided in its context. That state may change before execution, so the system must verify that the proposal is still valid before committing the action.</p><h4>6.4 Partial Failure Requires Recovery Semantics</h4><p>An agentic workflow may cross several systems that do not share a single database transaction.</p><p>A database update may succeed while event publication fails. A payment may complete while notification fails. A ticket may be created while the agent crashes before storing the ticket identifier.</p><p>The result is partial completion, which requires an explicit recovery strategy.</p><p>Depending on the operation, the system may:</p><p>• Retry the incomplete step<br>• Resume from the last confirmed state<br>• Query the external system for reconciliation<br>• Execute a compensating action<br>• Escalate for manual review<br>• Mark the workflow as terminally failed</p><p>Not every action can be rolled back.</p><p>Sending an email, publishing a message or transferring funds may be irreversible. In those cases, the system needs forward-recovery logic rather than assuming that rollback is always possible.</p><p>Recovery policy depends on distinguishing between:</p><p>• Reversible operations<br>• Compensatable operations<br>• Repeatable operations<br>• Irreversible operations<br>• Operations with ambiguous outcomes</p><p>That classification should influence approval, retry and recovery policy.</p><h3>7. Designing Stable Agent Control Loops</h3><p>An agent operates in a loop: it observes, decides, acts and checks the result. A stable control loop prevents endless retries, repeated actions and uncontrolled behavior by using clear stopping conditions, execution limits, validation and feedback.</p><h4>7.1 Feedback Loops Must Be Designed for Stability</h4><p>The control loop gives an agent its adaptability, but it can also create instability.</p><p>Consider a simple sequence:<br>The agent calls a slow API.<br>The call times out.<br>The planner interprets the timeout as failure.<br>The agent retries.<br>Additional calls increase the load.<br>Latency rises further.<br>More requests time out.<br>The agent increases its retry activity.<br>The system is now reinforcing its own failure, a positive feedback loop in which the response makes the original problem worse.</p><p>Agentic systems need stabilizing mechanisms:<br>• Exponential backoff<br>• Retry budgets<br>• Circuit breakers<br>• Concurrency limits<br>• Rate limits<br>• Work queues<br>• Load shedding<br>• Duplicate suppression<br>• Failure classification<br>• Escalation thresholds</p><p>Progress also needs an explicit definition.</p><p>A workflow that performs ten tool calls has not necessarily advanced further than one that performs two. Activity is not progress.</p><p>The control layer should determine whether each step:<br>• Reduces uncertainty<br>• Produces new evidence<br>• Changes the workflow state<br>• Resolves a dependency<br>• Moves toward a terminal condition</p><p>If the same plan, tool or result repeats without meaningful state change, the system should detect stagnation and stop.</p><h4>7.2 Agent Loops Need Execution Budgets</h4><p>Bounded autonomy should be enforced through explicit budgets.</p><p>A production agent may define limits for:<br>• Maximum model calls<br>• Maximum planning steps<br>• Maximum tool calls<br>• Maximum retries per operation<br>• Maximum concurrent operations<br>• Maximum retrieved documents<br>• Maximum token consumption<br>• Maximum financial cost<br>• Maximum wall-clock duration<br>• Maximum number of state-changing actions</p><p>These limits are not only cost controls; they are safety controls.<br>An agent with unlimited steps can enter loops. An agent with unlimited retrieval can flood its context with conflicting evidence. An agent with unrestricted tool use can amplify a small reasoning error across several systems.</p><p>The application must enforce the budget.</p><p>A prompt can request restraint. Only the system can guarantee a limit.</p><p>Controlling what an agent can do is only half of the problem.</p><p>The system must also control the information on which those actions are based.</p><h3>8. Information, Memory and Policy</h3><p>An agent needs reliable information, structured memory and clear rules. Information should include its source and freshness, memory should preserve useful context outside the prompt, and policy should define what the agent is allowed to do. Together, these prevent outdated decisions, lost context and unauthorized actions.</p><h4>8.1 Information Has Age, Provenance and Authority</h4><p>Retrieval quality is often discussed primarily in terms of semantic relevance.<br>Relevance is only one dimension.<br>A document can be highly relevant and still be unsafe to use because it is outdated, unofficial, superseded or applicable to a different jurisdiction.<br>Agentic decisions need richer information contracts.</p><p>Each retrieved item should carry metadata such as:<br>• source<br>• document_id<br>• document_version<br>• created_at<br>• effective_from<br>• effective_until<br>• retrieved_at<br>• owner<br>• authority_level<br>• classification<br>• supersedes<br>• superseded_by</p><p>The agent should not receive text detached from its operational context.</p><p>The system should be able to answer:<br>• Where did this information come from?<br>• Is the source authoritative?<br>• Which version was used?<br>• Was it valid at the time of the decision?<br>• Has it been superseded?<br>• How fresh must the information be for this action?<br>• Is corroboration required?</p><p>Freshness policy should depend on exposure.</p><p>A product recommendation may tolerate information that is several hours old.</p><p>A fraud decision may require data updated within minutes.<br>A financial transfer may require a new balance check immediately before execution.<br>Systems thinking connects information quality to the consequences of using it.<br>The same requirements apply not only to retrieved documents, but also to the information the agent retains and reuses as memory.</p><h4>8.2 Memory Is Not One Thing</h4><p>Agentic AI discussions often use the word “memory” as though it referred to a single mechanism.<br>In practice, several forms of memory have different reliability, privacy and governance requirements.</p><h4>Working Memory</h4><p>Temporary information used during the current reasoning cycle.<br>This can live in the prompt or execution context.</p><h4>Episodic Memory</h4><p>Records of previous interactions or completed workflows.</p><p>It can help the agent recognize patterns, but it must be filtered for relevance, retention and privacy.</p><h4>Semantic Memory</h4><p>Stable knowledge such as policies, domain rules and reference material.<br>This requires versioning, provenance and freshness management.</p><h4>Procedural Memory</h4><p>Instructions describing how a task should be performed.<br>In production, critical procedures should usually be implemented as deterministic workflow and policy logic rather than stored only as natural-language guidance.</p><h4>8.3 Policy Must Exist Outside the Model</h4><p>An agent should not be responsible for interpreting and enforcing every operational rule from natural language.<br>Important policies should be represented in deterministic components.</p><p>These rules cover areas such as:<br>• Which roles may call which tools<br>• Which data fields may be exposed<br>• Which actions require human approval<br>• Which operations are permitted in a given environment<br>• Which cost limits apply<br>• Which jurisdictions allow an action<br>• Which confidence thresholds trigger escalation<br>• Which workflow states allow execution</p><p>The model can help interpret ambiguous business context.<br>The policy layer should make the final allow-or-deny decision.<br>That creates a rule boundary the organization can test, audit and change independently of prompts and model versions.</p><h4>8.4 Approval Should Follow Exposure</h4><p>Human approval should not be added to every action.</p><p>That would turn the agent into an expensive interface for manual work.<br>Approval should be proportional to exposure.</p><p>Exposure is the potential harm caused by an incorrect action, considering its impact, reversibility, uncertainty and difficulty of recovery.</p><p>Factors that increase exposure include:<br>• Financial value<br>• Reversibility<br>• Legal consequences<br>• Data sensitivity<br>• Customer impact<br>• Operational blast radius<br>• Uncertainty in the evidence<br>• Difficulty of recovery</p><p>A low-exposure action may be executed automatically.</p><p>Examples include retrieving documentation, classifying a request or preparing a draft.</p><p>A high-exposure action may require approval. Examples include transferring funds, deleting customer data, modifying production infrastructure or publishing external content. Approval must be attached to a specific action plan.</p><p>Each approval record should capture:<br>• Who approved<br>• What action was approved<br>• Which parameters were approved<br>• What evidence was presented<br>• Which plan version was reviewed<br>• When the approval expires<br>• Whether execution matched the approved command<br>A generic approval message in a conversation history is not sufficient.<br>If the plan changes after approval, the system may need a new approval.</p><h3>9. Observability and Evaluation</h3><p>Observability shows what the agent did, why it made a decision and where a failure occurred. Evaluation measures whether the model, workflow and overall system behave correctly. Together, they help teams detect problems, improve performance and maintain accountability.</p><h4>9.1 Observability Must Preserve Decision Lineage</h4><p>Traditional observability focuses on availability, latency, errors and resource consumption.</p><p>Agentic systems also need observability that preserves decision lineage.<br>It is not enough to know that a tool was executed. We need to reconstruct the evidence, decisions and validations that led to it.</p><p>A complete trace may connect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IzO1WHX6sprpt4WLNMHMLQ.png" /><figcaption>Figure 5. Decision lineage and observability in an Agentic AI system. Original concept and content by Ediz Najim. Visual designed using Canva.</figcaption></figure><p>Such a trace supports debugging, audit, evaluation and incident response.</p><p>Without this decision lineage, several very different failures may appear identical:<br>• The model reasoned incorrectly.<br>• Retrieval returned irrelevant evidence.<br>• The evidence was relevant but stale.<br>• Memory introduced an incorrect assumption.<br>• Policy validation was missing.<br>• The tool accepted invalid input.<br>• The action succeeded but state persistence failed.<br>• The workflow retried an already completed operation.</p><p>Each failure requires a different correction. Observability must make the failure boundary visible.</p><h4>9.2 Evaluation Must Cover the Whole System</h4><p>Agentic AI is often evaluated through answer quality or task completion.</p><p>That is not enough.</p><p>A system may complete the task while violating policy, using stale information or leaving an unrecoverable state behind.<br>Evaluation should occur at several levels.</p><h4>Model-Level Evaluation</h4><p>Measures reasoning and generation quality:<br>• Tool-selection accuracy<br>• Argument accuracy<br>• Planning quality<br>• Groundedness<br>• Hallucination rate</p><h4>Workflow-Level Evaluation</h4><p>Measures whether the control loop behaved correctly:<br>• Valid state transitions<br>• Number of unnecessary steps<br>• Loop frequency<br>• Recovery success<br>• Duplicate-action rate<br>• Escalation accuracy</p><h4>System-Level Evaluation</h4><p>Measures operational behaviour:<br>• End-to-end latency<br>• Timeout rate<br>• Retry volume<br>• Idempotency violations<br>• Cost per completed task<br>• Resource consumption<br>• Availability</p><h4>Business-Level Evaluation</h4><p>Measures whether the intended outcome was achieved:<br>• Resolution rate<br>• Financial accuracy<br>• Customer impact<br>• Policy compliance<br>• Human-review burden<br>• Cost of errors</p><h4>Governance-Level Evaluation</h4><p>Measures whether the system remained accountable:<br>• Approval correctness<br>• Audit completeness<br>• Data-access compliance<br>• Explainability of actions<br>• Trace coverage</p><p>A model can perform well while the system performs badly.</p><p>Model quality and system quality must therefore be measured separately.</p><p>Evaluating the whole system also changes the questions architects must ask during design.</p><h3>10. From Model-Centered to System-Centered Design</h3><p>Model-centered projects begin with questions such as:<br>• Which model should we use?<br>• How should we write the prompt?<br>• How large should the context window be?<br>• Should we use one agent or several?<br>• How can we improve planning?</p><p>These questions matter. They are not sufficient.</p><p>System-centered design asks:<br>• Where does authoritative state live?<br>• Which component owns each transition?<br>• What survives a restart?<br>• How are concurrent updates handled?<br>• Which actions are idempotent?<br>• Which actions are reversible?<br>• What happens when execution succeeds but acknowledgement fails?<br>• How is stale information detected?<br>• Who can authorize each action?<br>• What triggers human approval?<br>• How is the decision path reconstructed?<br>• What stops the agent when progress ends?<br>• How are partially completed workflows recovered?<br>• Who owns the final outcome?</p><p>These may not be the most impressive questions in a demonstration.<br>They are the questions that determine whether the system survives production.</p><h3>11. A Systems-Oriented Agent Architecture</h3><p>A production Agentic AI architecture should separate responsibilities clearly.</p><h4>Interaction Layer</h4><p>Receives the goal, authenticates the requester and establishes the execution context.</p><h4>State and Workflow Layer</h4><p>Owns workflow state, transitions, versioning, execution history and recovery checkpoints.</p><h4>Context and Evidence Layer</h4><p>Retrieves information, validates provenance, applies freshness rules and assembles context.</p><h4>Reasoning Layer</h4><p>Uses the model to interpret the goal, evaluate evidence and propose structured actions.</p><h4>Policy and Validation Layer</h4><p>Checks schemas, permissions, budgets, workflow rules, business constraints and approval requirements.</p><h4>Command Layer</h4><p>Converts an approved proposal into a durable, uniquely identified execution command.</p><h4>Tool Execution Layer</h4><p>Invokes controlled interfaces with explicit timeout, idempotency, authorization and error semantics.</p><h4>Observation Layer</h4><p>Records traces, metrics, decisions, tool results, latency, cost and business outcomes.</p><h4>Recovery Layer</h4><p>Handles retries, reconciliation, compensation, partial completion and manual escalation.</p><h4>Human Oversight Layer</h4><p>Manages approvals, interventions, exceptions and accountability.</p><p>The model remains central to reasoning.</p><p>It is not the center of control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyqSe7fpR7oNiWnaIkV9GQ.png" /><figcaption><em>Figure 6. A systems-oriented architecture for production-ready Agentic AI. Original concept and content by Ediz Najim. Visual designed using Canva.</em></figcaption></figure><h3>12. Stronger Models Do Not Repair Weak Systems</h3><p>There is a common belief that Agentic AI will become reliable mainly because models will continue to improve.</p><p>Better models will reduce some reasoning errors. They will not repair weak architecture.</p><p>• A larger model cannot provide idempotency.<br>• A longer context window cannot replace durable workflow state.<br>• A better planner cannot enforce authorization.<br>• A stronger reasoning model cannot resolve an ambiguous external side effect unless the system recorded an operation identifier.<br>• A more accurate model cannot determine whether a policy is current unless the architecture provides version and provenance metadata.<br>• A capable model cannot recover from an invalid state transition that the application allowed.</p><p>Stronger models may even increase the risk created by weak systems.</p><p>They can produce more convincing plans, use more tools, operate across longer workflows and take actions with greater speed.</p><p>That increases the blast radius of architectural mistakes.</p><p>Model quality and system quality are separate dimensions.<br>Reliable Agentic AI requires both.</p><h3>Conclusion</h3><p>Agentic AI should not be judged by how impressive it appears when every dependency works.</p><p>It should be judged by how it behaves when information is incomplete, external systems are slow, responses are lost, actions are repeated, state changes concurrently and consequences are real.</p><p>That requires a wider field of view.</p><p>We must examine not only the model, but also the state, contracts, feedback loops, execution boundaries, information flows, recovery mechanisms and accountability structures around it.</p><p>That is what systems thinking brings to Agentic AI.</p><p>The central principle remains simple:<br>The model proposes. The system executes. The human remains accountable.</p><p>Agentic AI becomes production-ready not when the model appears intelligent, but when the entire system remains controlled, recoverable and understandable under failure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ece5dbf061c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/softtechas/systems-thinking-for-agentic-ai-2ece5dbf061c">Systems Thinking for Agentic AI</a> was originally published in <a href="https://medium.com/softtechas">Softtech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From AI Demos to Production Agent Systems]]></title>
            <link>https://medium.com/@ediznajim/from-ai-demos-to-production-agent-systems-bbf099085f13?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbf099085f13</guid>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 23:01:03 GMT</pubDate>
            <atom:updated>2026-06-15T23:01:03.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hR4mM1tnTmq20erk5ukhQ.png" /><figcaption>From AI Demos to Production Agent Systems</figcaption></figure><p>Why calling a model is easy and why building a reliable system around it is an entirely different engineering problem.</p><p>After more than twenty years in software engineering, I have watched the same pattern repeat itself with every major technology wave. The first demos look impressive. Stakeholders get excited. Teams rush into production. Then reality arrives.</p><p>With AI agents, that gap is more visible and more consequential than with almost any technology I have seen before. Not because the models are weak. But because the engineering discipline required to wrap them into reliable production systems is still being understood.</p><p>This article draws directly from what I learned writing <em>Systems Thinking for Agentic AI</em>. It is for software engineers and architects who are working with systems they can actually trust in production.</p><h3>The Demo Gap</h3><p>A demo may feel impressive because the model answers fluently, explains code, summarizes text, or follows an instruction. That fluency is genuine. Large language models are remarkably capable at language tasks. But when the same idea moves closer to a real application, the missing parts become visible.</p><p>Many early AI demos create the illusion that the LLM is the product. In real systems, that is not true. The model is usually one component inside a larger architecture. And it is the architecture, not the model, that determines whether the system is actually usable.</p><p><strong><em>“The model may make the system feel intelligent, but the architecture makes it usable.”</em></strong></p><p><strong><em>— </em></strong>Systems Thinking for Agentic AI, Chapter 1</p><p>On its own, an LLM has real limits. It may not know current information. It may not have access to private enterprise data. It can produce fluent but incorrect answers. It may fail to follow a required structure every time. It cannot safely execute backend operations by itself. And it does not automatically behave like a reliable software system.</p><p>Once you accept that the model is one component, not the whole system , the engineering questions become clear. The question is no longer only <em>“Can the model answer this?”</em> The better question is: <em>“How should the surrounding system be designed so the model becomes useful, safe, measurable, and reliable?”</em></p><h3>Five Ways AI Projects Fail Before Production</h3><p>These are not model problems. They are system design problems and they appear in nearly every AI project that skips the architectural layer.</p><ul><li><strong>Prompts</strong> become trial-and-error experiments. Without versioning, evaluation, and structured testing, prompt changes have unpredictable effects. A change that improves one case silently breaks another.</li><li><strong>Hallucinations</strong> feel unpredictable. They are not. Hallucinations follow patterns related to token probability, missing grounding, and insufficient retrieval. Systems that treat them as random will never reduce them systematically.</li><li><strong>Retrieval </strong>is added without enough attention to chunking, ranking, or grounding. Many teams bolt on a vector database, call it RAG, and wonder why the answers are still unreliable. RAG is a system pattern involving document preparation, chunking strategy, embedding models, hybrid search, re-ranking, context assembly, and prompt integration.</li><li><strong>Tool calls</strong> are wired into systems before validation, permissions, and failure handling are clear. When the model can invoke external operations, the cost of a wrong step rises quickly. Permissions, validation and failure modes must be designed before tools are connected, not after.</li><li><strong>Observability</strong> arrives too late. After the workflow has already become hard to debug. In agentic systems, a correct final answer does not tell you whether the path to that answer was correct, efficient, or safe. Observability must be designed into the loop from the start.</li></ul><h3>What an AI Agent Actually Is</h3><p>The term <em>agent</em> is used widely but not always precisely. In many discussions, the label is applied to any application built around a language model. That is too broad to be useful.</p><p>An AI agent is a system that uses an AI model as part of a control loop to pursue a task through intermediate steps. Instead of producing one answer and stopping, the system can interpret a request, decide what should happen next, invoke external capabilities, observe results, and continue until the objective has been reached or a stopping condition applies.</p><p>The defining feature is the loop:</p><p><strong>Think</strong> — Select the next action or answer directly</p><p><strong>Act</strong> — Execute a tool, retrieve data, or respond</p><p><strong>Observ</strong>e — Inspect the result and update state</p><p><strong>Continue</strong> — Decide next step or apply stopping condition</p><p>This is not a human mind at work. It is a system following a controlled process.</p><p>The model chooses the next step. The runtime controls the loop, tools, state, validation, and stopping rules. Without this control, an agent is only a model making one decision after another. The problem begins when the model keeps deciding, but the system does not clearly control which tools it can use, what state it keeps, when it must stop, or how its results are checked.</p><p>This may look impressive in a demo. It is not reliable in production. A useful agent loop needs clear limits: maximum steps, allowed actions, validation rules, retry rules, and stopping conditions.</p><p>The loop gives the agent flexibility. The boundaries make that flexibility reliable.</p><h3>Production Architecture Starts with Boundaries</h3><p>A production agent system is not a single model surrounded by optional features. It is a structured runtime in which reasoning, orchestration, execution, retrieval, persistence, and operational control remain distinct enough to manage.</p><p>The important point is ownership. In a well-designed system, you can answer these questions clearly: Which component decides? Which component validates? Which component executes? Which component stores state? Which component records evidence?</p><p>When an agent fails, “the model decided” is not a root cause. It is a sign that the architecture did not assign responsibility clearly enough.</p><p>🔀<strong>Orchestration</strong> : Coordinates the workflow. Manages the execution loop. Decides what should happen next. Turns capabilities into agent behavior.</p><p>🧠<strong>LLM Layer</strong> : Provides reasoning and generation. Interprets context, proposes decisions, generates responses. Does not execute operations directly.</p><p>📚<strong>Retrieval </strong>: Supplies knowledge from documents, databases, or search. Grounding reduces hallucination and makes the system useful in knowledge-heavy domains.</p><p>🔧<strong>Tool Execution</strong> : Connects the system to external operations under control. The model proposes; the application decides whether the request is valid and executes it.</p><p>💾<strong>Memory </strong>: Preserves useful continuity across steps and interactions. Must be carefully managed — not everything the system has ever seen should be silently injected.</p><p>📡<strong>Observability </strong>: Records what happened, why, and how the system reached its answer. A correct final answer does not guarantee a correct path was taken.</p><p>A weak design connects these components loosely and hopes the model will behave well. A stronger design assigns responsibility clearly. When those responsibilities are mixed together, debugging becomes guesswork. When they are separated, the system can be inspected and improved.</p><h3>Reliability Is a Runtime Control Problem</h3><p>Reliability in traditional software is usually tied to deterministic behavior. Given the same input and the same system state, the software produces the same output. When something goes wrong, the cause is often traceable to code, configuration, or infrastructure.</p><p>LLM systems introduce a different kind of uncertainty. The model operates on probabilities rather than fixed rules. It can produce variable output, interpret the same instruction differently across runs, or generate an answer that sounds correct while still being wrong. The system may fail without crashing — it can return a fluent response, a valid-looking structure, or a plausible action, yet still be incorrect in a way that matters.</p><p>In an LLM system, reliability also includes correct tool selection, valid arguments, grounded answers, stable workflow behavior, and safe handling of ambiguity. A system can be operationally healthy and still be behaviorally unreliable.</p><h3>Practical Rules for Reliable Agent Systems</h3><ul><li><strong>Treat the model as a reasoning component, not a trusted execution authority.</strong> Let it interpret, propose, and summarize — but enforce system rules outside the model.</li><li><strong>Validate at every boundary. </strong>Inputs, outputs, tool arguments, tool results, memory writes, and workflow transitions should all be checked against explicit contracts.</li><li><strong>Separate trusted instructions from untrusted content. </strong>User input, retrieved text, and external data should not silently become execution policy.</li><li><strong>Classify tools by risk. </strong>Read-only tools, state-changing tools, and high-impact actions should not all follow the same approval path.</li><li><strong>Design for safe degradation. </strong>A system that can return a partial result, escalate, or stop safely is more trustworthy than one that always tries to complete the task at any cost.</li><li><strong>Monitor behavior as well as infrastructure. </strong>A working service can still be an unreliable AI system if it retrieves weak context, calls the wrong tool, produces invalid structure, or ignores stopping conditions.</li></ul><p><strong><em>“Reliability in agent systems is not achieved by trusting the model more. It is achieved by trusting the surrounding system to constrain, validate, observe, and recover from model behavior.”</em></strong></p><p>— Systems Thinking for Agentic AI, Chapter 11</p><h3>The Shift That Changes Everything</h3><p>AI is not one technology. It is a broad class of computational behavior. Once you understand how tokens, embeddings, prompts, retrieval, tools, memory, and agent loops fit together, AI becomes less mysterious and more architectural.</p><p>That shift is what the “<strong>Systems Thinking for Agentic AI” </strong>book<strong> </strong>is built on. Not hype. Not demos. But the engineering discipline required to design AI systems with the same care we apply to every other serious piece of software.</p><p>A demo requires a capable model. A production system requires a capable team that understands the architecture around it. The model is one component. The system is everything.</p><p><strong>Systems Thinking for Agentic AI</strong></p><p>A Software Architect’s Guide to Building Reliable LLM and Agent Systems. First Edition, 2026. Available on Amazon KDP.</p><p><a href="https://www.amazon.com/dp/B0GZSK31J1">https://www.amazon.com/dp/B0GZSK31J1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbf099085f13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Core Engine for Correctness in Low-Latency Systems]]></title>
            <link>https://medium.com/@ediznajim/the-core-engine-for-correctness-in-low-latency-systems-647980b13ed0?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/647980b13ed0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 10:39:03 GMT</pubDate>
            <atom:updated>2026-04-08T10:39:03.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yzVFuydcGTGcWVpEG-9kA.png" /></figure><p>Low-latency systems rarely fail because they are slow. They fail because multiple execution paths are allowed to mutate the same state concurrently.</p><p>The symptoms are familiar:</p><ul><li>Fills after cancel</li><li>Negative remaining quantities</li><li>Race conditions that disappear under debugging</li><li>Incidents that “cannot be reproduced”</li></ul><p>The fix is ownership.</p><blockquote><em>Partition state into shards and enforce a single writer per shard.</em></blockquote><p>This engine design turns correctness from a <em>best-effort property</em> into a <em>mechanical guarantee</em>.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pNKIj_1svg4RCTqR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*bQ3wJHPZstW66Sq8" /></figure><h3>Sharding: scaling through ownership, not contention</h3><p>Sharding means splitting a big dataset or workload into smaller parts called shards, and distributing them across multiple machines (or workers), so the system can scale.</p><p>In a low-latency engine, sharding means:</p><ul><li>Each shard owns a subset of the domain state (typically per symbol / instrument)</li><li>Commands for that state go to that shard only</li><li>Only the shard’s writer is allowed to mutate that state</li></ul><h3>Shard key</h3><p>The shard key is typically a stable identifier (e.g. symbolId)</p><pre>public final class ShardRouter {<br>    private final int shardCount;<br>public ShardRouter(int shardCount) {<br>        if (shardCount &lt;= 0) throw new IllegalArgumentException(&quot;shardCount must be &gt; 0&quot;);<br>        this.shardCount = shardCount;<br>    }<br>    public int shardForSymbol(long symbolId) {<br>        return Math.floorMod(Long.hashCode(symbolId), shardCount);<br>    }<br>}</pre><h3>Technical implications</h3><ul><li>Parallelism comes from running multiple shards concurrently</li><li>Correctness comes from ensuring a symbol always maps to the same shard</li><li>No cross-thread coordination is required because a symbol’s book never has two writers</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*qFntuJsF1FixRZIm" /></figure><h3>Components: What each piece does (and what it must NOT do)</h3><h3>1) Producers</h3><p>Any ingress source:</p><ul><li>REST</li><li>FIX</li><li>Adapters</li><li>Tests</li></ul><p>They do not touch the order book. They submit commands only.</p><h3>2) ShardedEngine</h3><p>The trade engine is an orchestration boundary, not a business component.</p><p>Responsibilities:</p><ul><li>route commands to the correct shard</li><li>apply backpressure policy</li><li>expose event draining and metrics</li></ul><pre>public final class ShardedEngine {<br>private final ShardRouter router;<br>    private final EventChannel eventChannel;<br>    private final List&lt;CommandChannel&gt; commandChannels = new ArrayList&lt;&gt;();<br>    public ShardedEngine(int shardCount, int queueCapacity, BackpressurePolicy policy) {<br>        this.router = new ShardRouter(shardCount);<br>        this.eventChannel = new InMemoryEventChannel(<br>                Math.max(1024, shardCount * queueCapacity * 4)<br>        );<br>        for (int i = 0; i &lt; shardCount; i++) {<br>            CommandChannel ch = new InMemoryCommandChannel(queueCapacity);<br>            commandChannels.add(ch);<br>            ShardWriter w = new ShardWriter(i, ch, eventChannel);<br>            Thread t = new Thread(w, &quot;writer-&quot; + i);<br>            t.start();<br>        }<br>    }<br>}</pre><h3>3) CommandChannel</h3><p>A bounded queue per shard — the shard’s mailbox.</p><pre>public final class InMemoryCommandChannel implements CommandChannel {<br>private final BlockingQueue&lt;CommandEnvelope&gt; queue;<br>    public InMemoryCommandChannel(int capacity) {<br>        this.queue = new ArrayBlockingQueue&lt;&gt;(capacity);<br>    }<br>    @Override<br>    public boolean offer(CommandEnvelope envelope) {<br>        return queue.offer(envelope);<br>    }<br>    @Override<br>    public int poll(CommandConsumer consumer, int limit) {<br>        int count = 0;<br>        while (count &lt; limit) {<br>            CommandEnvelope env = queue.poll();<br>            if (env == null) break;<br>            consumer.onCommand(env);<br>            count++;<br>        }<br>        return count;<br>    }<br>}</pre><h3>4) Writer (Single Writer per shard)</h3><p>Each shard has exactly one writer thread.</p><p>The writer:</p><ul><li>polls the command channel</li><li>applies commands sequentially</li><li>is the only place state mutation occurs</li></ul><p>This is the linearization point of the entire system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*RdCmQKPLNnyC1v9v" /></figure><h3>5) OrderBook</h3><p>The matching engine and domain model.</p><ul><li>intentionally non-concurrent</li><li>owns all matching logic</li><li>produces domain events</li></ul><h3>6) EventChannel + Consumers</h3><p>Events are immutable facts.</p><p>Consumers:</p><ul><li>read asynchronously</li><li>perform side effects (persist, risk, notify)</li><li>never mutate trading state</li></ul><h3>Request Flow (end-to-end)</h3><h3>Step 1 — Commands are submitted</h3><p>Commands express intent only.</p><pre>public sealed interface Command permits PlaceOrderCmd, CancelOrderCmd {<br>    long symbolId();<br>}</pre><pre>public record PlaceOrderCmd(<br>        long symbolId,<br>        long orderId,<br>        Side side,<br>        int price,<br>        int qty<br>) implements Command {}</pre><pre>public record CancelOrderCmd(<br>        long symbolId,<br>        long orderId<br>) implements Command {}</pre><h3>Step 2 — TradeEngine routes to the shard</h3><pre>public void submit(Command cmd) {<br>    int shardId = router.shardForSymbol(cmd.symbolId());<br>    CommandEnvelope env = new CommandEnvelope(cmd, System.nanoTime());<br>boolean offered = commandChannels.get(shardId).offer(env);<br>    if (!offered &amp;&amp; policy == BackpressurePolicy.REJECT) {<br>        eventChannel.publish(<br>            new OrderRejectedEvt(cmd.symbolId(), -1, &quot;BACKPRESSURE&quot;)<br>        );<br>    }<br>}</pre><h3>Step 3 — Writer polls the CommandChannel and consume orders</h3><pre>while (!Thread.currentThread().isInterrupted()) {<br>    int processed = commandChannel.poll(consumer, POLL_LIMIT);<br>    if (processed == 0) {<br>        Thread.onSpinWait();<br>    }<br>}</pre><p>This establishes:</p><ul><li>total ordering</li><li>deterministic execution</li><li>no interleaving</li></ul><h3>Step 4 — Writer mutates state via OrderBook</h3><pre>private OrderBook book(long symbolId) {<br>    return books.computeIfAbsent(symbolId, k -&gt; new OrderBook());<br>}<br>private void handle(Command cmd) {<br>    if (cmd instanceof PlaceOrderCmd c) {<br>        book(c.symbolId()).place(c, sink);<br>    } else if (cmd instanceof CancelOrderCmd c) {<br>        book(c.symbolId()).cancel(c, sink);<br>    }<br>}</pre><h3>Step 5 — OrderBook uses NavigableMaps</h3><pre>private final NavigableMap&lt;Integer, ArrayDeque&lt;Order&gt;&gt; buys =<br>        new TreeMap&lt;&gt;(Comparator.reverseOrder());<br>private final NavigableMap&lt;Integer, ArrayDeque&lt;Order&gt;&gt; sells =<br>        new TreeMap&lt;&gt;();<br>private final Map&lt;Long, OrderRef&gt; orderIndex = new HashMap&lt;&gt;();<br>private long seq = 0;</pre><ul><li>Best price lookup</li><li>FIFO within price level</li><li>O(1) cancel via index</li></ul><h3>Step 6 — Events are published and consumed</h3><pre>public final class InMemoryEventChannel implements EventChannel {<br>private final BlockingQueue&lt;DomainEvent&gt; queue;<br>    public InMemoryEventChannel(int capacity) {<br>        this.queue = new ArrayBlockingQueue&lt;&gt;(capacity);<br>    }<br>    @Override<br>    public boolean publish(DomainEvent event) {<br>        return queue.offer(event);<br>    }<br>    @Override<br>    public int poll(EventConsumer consumer, int limit) {<br>        int count = 0;<br>        while (count &lt; limit) {<br>            DomainEvent event = queue.poll();<br>            if (event == null) break;<br>            consumer.onEvent(event);<br>            count++;<br>        }<br>        return count;<br>    }<br>}</pre><h3>Why this engine is correct ?</h3><ul><li>Sharding enforces ownership</li><li>Single writer enforces determinism</li><li>Commands define clean intent boundaries</li><li>Events isolate side effects</li></ul><p>There is:</p><ul><li>no shared mutable state</li><li>no lock contention</li><li>no race recovery logic</li></ul><p>Correctness is structural.</p><h3>Why this system is fast</h3><p>Because it combines:</p><ul><li>Sharding for parallelism</li><li>Single writers for determinism</li><li>Commands for clarity</li><li>Events for isolation</li><li>Bounded queues for latency control</li><li>Simple data structures for predictable cost</li></ul><h3>Latency</h3><p>In low-latency systems, the most dangerous failure mode is allowing queues to grow without bound.</p><p>This leads to unpredictable tail latency, where p99/p999 response times explode even when average latency looks stable.</p><p>This architecture avoids that failure mode by treating bounded queues as a first-class latency-control primitive.</p><p>Additional latency optimizations:</p><ul><li>no locks on the hot path</li><li>no cross-thread book sharing</li><li>spin-wait instead of sleep/wakeup jitter</li><li>cache-local state per writer</li></ul><p>Latency is measured as two independent components:</p><pre>long queueWait = now - env.enqueuedNanos();<br>long handleNanos = System.nanoTime() - start;</pre><h3>Throughput</h3><p>Throughput scales by:</p><ul><li>increasing shard count</li><li>distributing symbols evenly</li><li>keeping per-shard work bounded</li></ul><p>Scaling comes from parallel ownership, not concurrent mutation.</p><h3>Final Mental Model</h3><pre>Producer<br>  → TradeEngine<br>    → ShardRouter<br>      → CommandChannel<br>        → Single Writer<br>          → OrderBook<br>            → Domain Events<br>              → EventChannel<br>                → Consumers</pre><p>Every arrow is:</p><ul><li>explicit</li><li>owned</li><li>deterministic</li></ul><h3>Backpressure: protecting latency under load</h3><p>In low-latency systems, the worst thing you can do is “accept everything” and let queues grow without limit.</p><p>That creates:</p><ul><li>unpredictable tail latency (p99 / p999 explode)</li><li>GC pressure (if queues are unbounded)</li><li>delayed cancels (a direct risk issue)</li><li>timeouts and cascading failures upstream</li></ul><p>This engine design already has the right base primitive: bounded queues.</p><h3>Bounded queues are a latency guarantee</h3><p>CommandChannel is bounded (ArrayBlockingQueue), which means:</p><ul><li>memory usage is predictable</li><li>queue wait time is measurable</li><li>overload is visible immediately</li></ul><pre>public final class InMemoryCommandChannel implements CommandChannel {<br>    private final BlockingQueue&lt;CommandEnvelope&gt; queue;<br>public InMemoryCommandChannel(int capacity) {<br>        this.queue = new ArrayBlockingQueue&lt;&gt;(capacity);<br>    }<br>    @Override<br>    public boolean offer(CommandEnvelope envelope) {<br>        return queue.offer(envelope); // returns false when full<br>    }<br>}</pre><p>Bounded queues convert overload from a hidden latency problem into an explicit control decision.</p><h3>Backpressure policies (REJECT / BLOCK / DROP)</h3><p>Under overload, the system must decide what happens when a shard’s queue is full.</p><p>There are three classic policies:</p><h3>A) REJECT (best for correctness + bounded tail latency)</h3><ul><li>fail fast</li><li>upstream can retry or shed load</li><li>tail latency remains bounded</li></ul><pre>public void submit(Command cmd) {<br>    int shardId = router.shardForSymbol(cmd.symbolId());<br>    CommandEnvelope env = new CommandEnvelope(cmd, System.nanoTime());<br>    boolean offered = commandChannels.get(shardId).offer(env);<br>    if (!offered) {<br>        if (policy == BackpressurePolicy.REJECT) {<br>            eventChannel.publish(<br>                new OrderRejectedEvt(cmd.symbolId(), -1, &quot;BACKPRESSURE&quot;)<br>            );<br>        }<br>    }<br>}</pre><p>This policy is usually the correct choice for trading cores.</p><h3>B) BLOCK (best for “must accept”, worst for latency)</h3><ul><li>producer thread waits</li><li>prevents loss</li><li>introduces unpredictable response times</li></ul><p>If ever required, this would be implemented as:</p><pre>public void put(CommandEnvelope env) throws InterruptedException {<br>    queue.put(env); // blocks until space is available<br>}</pre><p>This is generally not suitable for low-latency trading paths.</p><h3>C) DROP (rare for trading cores)</h3><ul><li>commands or events are silently dropped</li><li>sometimes acceptable for telemetry</li><li>not acceptable for trading correctness</li></ul><h3>Key Benefits in One Place</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*WQ72ZDKJsCN16_fm" /></figure><h3>Summary</h3><p>Low-latency systems rarely fail because they are slow; they fail because multiple execution paths mutate the same state concurrently. The result is race conditions, inconsistent data, and incidents that cannot be reproduced. Locks and CAS try to fix these problems after contention appears, but they don’t remove the root cause.</p><p>The core solution is ownership. State is sharded (often by symbol), and each shard is mutated by exactly one writer. Commands express intent, shard routing enforces deterministic ownership, the single writer provides total ordering, and the OrderBook remains intentionally non-concurrent. Events are emitted as immutable facts, isolating side effects from the critical path.</p><p>This design delivers predictable latency and scalable throughput. Bounded queues and explicit backpressure control tail latency, while throughput scales via parallel shards rather than concurrent mutation. Correctness becomes structural — not best-effort.</p><p>For developers working on real-time systems:</p><ul><li>How do you handle multiple threads changing data ?</li><li>Have you tried patterns where only one thread can write to certain data, and what worked or didn’t work for you ?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=647980b13ed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Public and Private Keys: The Foundation of Secure Distributed Systems]]></title>
            <link>https://medium.com/@ediznajim/public-and-private-keys-the-foundation-of-secure-distributed-systems-4e27ab53c76e?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e27ab53c76e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 22:25:53 GMT</pubDate>
            <atom:updated>2026-03-12T22:25:53.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vZEAHydGN4Kawm_tuARoQ.png" /><figcaption>Public and Private Keys</figcaption></figure><h3>How Public Key vs Private Key Actually Work</h3><p>Modern systems rely heavily on cryptography to secure communication, protect data, and verify identity.</p><p>Behind many of these mechanisms are two simple concepts:</p><p>Private Keys Public Keys</p><p>These two keys work together to create one of the most important mechanisms in modern computing: asymmetric cryptography.</p><p>But what do they actually do?</p><p>And how are they used in real systems?</p><p>Let’s break it down.</p><h3>The Core Idea</h3><p>Traditional encryption uses one key.</p><pre>Encrypt → Secret Key → Decrypt</pre><p>Both parties must share the same key.</p><p>This creates a problem:</p><p>How do you securely share the key in the first place?</p><p>Public-key cryptography solves this.</p><p>Instead of one key, it uses two keys.</p><pre>Public Key<br>Private Key</pre><p>They are mathematically related but serve different roles.</p><h3>The Two Keys</h3><h3>Public Key</h3><p>The public key can be shared with anyone.</p><p>It is used to:</p><p>• encrypt data • verify signatures</p><p>Example:</p><pre>You publish your public key on a server.<br>Anyone can use it.</pre><h3>Private Key</h3><p>The private key must never be shared.</p><p>It is used to:</p><p>• decrypt data • create signatures</p><p>Example:</p><pre>Only the owner of the private key can decrypt messages<br>encrypted with the public key.</pre><h3>Example: Secure Message</h3><p>Imagine Alice wants to send a secret message to Bob.</p><h3>Step 1</h3><p>Bob generates two keys:</p><pre>Public Key (shared)<br>Private Key (secret)</pre><p>Bob sends Alice his public key.</p><h3>Step 2</h3><p>Alice encrypts the message using Bob’s public key.</p><pre>EncryptedMessage = Encrypt(message, BobPublicKey)</pre><h3>Step 3</h3><p>Bob receives the message and decrypts it using his private key.</p><pre>message = Decrypt(EncryptedMessage, BobPrivateKey)</pre><p>Only Bob can decrypt it.</p><p>Even Alice cannot decrypt it after encryption.</p><h3>Digital Signatures</h3><p>Public/private keys are also used for identity verification.</p><p>Instead of encrypting a message, the sender signs it.</p><h3>Step 1</h3><p>Alice signs the message using her private key.</p><pre>signature = Sign(message, AlicePrivateKey)</pre><h3>Step 2</h3><p>Anyone can verify the signature using Alice’s public key.</p><pre>Verify(message, signature, AlicePublicKey)</pre><p>If verification succeeds:</p><pre>The message really came from Alice<br>and was not modified.</pre><h3>Real-World Examples</h3><p>Public/private keys are everywhere in modern systems.</p><h3>HTTPS / TLS</h3><p>When you open:</p><pre>https://example.com</pre><p>Your browser uses public-key cryptography to securely exchange keys with the server.</p><p>This protects: • passwords • cookies • credit card information</p><h3>SSH</h3><p>When connecting to a server:</p><pre>ssh user@server</pre><p>Authentication often works using a key pair:</p><pre>~/.ssh/id_rsa       (private key)<br>~/.ssh/id_rsa.pub   (public key)</pre><p>The server stores the public key.</p><p>The client proves identity using the private key.</p><h3>JWT Signing</h3><p>Many backend systems sign tokens using private keys.</p><p>Example:</p><pre>RS256 JWT</pre><p>Flow:</p><pre>Server signs token with Private Key<br>Clients verify token using Public Key</pre><p>This allows distributed systems to verify tokens without sharing secrets.</p><h3>Git</h3><p>Git commits can be signed using GPG keys.</p><pre>Private key → sign commit<br>Public key → verify commit</pre><p>This proves the commit came from the real author.</p><h3>Why This Matters for System Architects</h3><p>Public/private key cryptography enables:</p><p>• secure communication • distributed authentication • trust without shared secrets • secure microservice communication</p><p>It is the foundation behind:</p><pre>TLS<br>OAuth<br>JWT<br>SSH<br>Blockchain<br>Secure APIs</pre><p>Without asymmetric cryptography, modern internet infrastructure would not work.</p><h3>A Simple Way to Remember</h3><p>Think of it like a mailbox.</p><pre>Public Key  = Mail slot anyone can drop letters into<br>Private Key = The only key that opens the mailbox</pre><p>Anyone can send you a message. But only you can open it.</p><h3>Final Thought</h3><p>Public-key cryptography solved one of the biggest problems in distributed systems:</p><p>How do you establish trust between parties that have never met?</p><p>By separating encryption and decryption into two different keys, systems can communicate securely across the open internet.</p><p>It’s one of the simplest ideas in cryptography and one of the most powerful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e27ab53c76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Java HTTP: Client & Server in Harmony with Virtual Threads]]></title>
            <link>https://medium.com/@ediznajim/modern-java-http-client-server-in-harmony-with-virtual-threads-d8eed971ae84?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8eed971ae84</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[java-virtual-threads]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 12:49:17 GMT</pubDate>
            <atom:updated>2026-03-09T12:49:17.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPyoZ_G5JgOFUXcqLlAVlg.jpeg" /></figure><p><strong>Modern Java HTTP: Client &amp; Server in Harmony with Virtual Threads</strong></p><p>With the evolution of Java from JDK 11 to JDK 21+, the platform’s built-in HTTP capabilities have matured into a robust and practical toolkit. Without external frameworks, developers can build scalable HTTP clients and lightweight services using only the JDK.</p><p>At the heart of this modern stack:</p><ul><li>HttpClient → the standard, modern HTTP client introduced in JDK 11</li><li>HttpServer → a lightweight embeddable HTTP server included in the JDK</li><li>Virtual Threads (Project Loom) → a breakthrough concurrency model that makes blocking I/O scale efficiently</li></ul><p>Together, these components allow developers to write simple blocking code that can still scale to very high concurrency levels.</p><h3>Java’s Built-in HTTP Server (Simple and Lightweight)</h3><p>com.sun.net.httpserver.HttpServer is a small HTTP server built directly into the JDK. It is useful for:</p><ul><li>internal endpoints</li><li>lightweight services</li><li>mock servers</li><li>development tools</li><li>embedded utilities</li></ul><p>It is not intended to replace full production web frameworks, but it is extremely convenient for small services.</p><h3>Example</h3><pre>HttpServer server = HttpServer.create(new InetSocketAddress(8080), 50);<br>server.createContext(&quot;/&quot;, exchange -&gt; {<br>    String response = &quot;Hello from Java HTTP Server!&quot;;<br>    exchange.sendResponseHeaders(200, response.getBytes().length);<br>    try (var os = exchange.getResponseBody()) {<br>        os.write(response.getBytes());<br>    }<br>});<br><br>server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());<br>server.start();</pre><h3>Key Concepts</h3><ul><li>Backlog (50) The backlog controls how many incoming TCP connections can wait in the queue before they are accepted by the server. If the queue fills faster than requests are processed, new connections may be rejected by the operating system.</li><li>Executor The executor defines how requests are processed. Using a virtual-thread executor allows the server to handle a very large number of concurrent requests while keeping the code simple.</li></ul><h3>Java HttpClient (Modern, Async, and Pooled)</h3><p>Since JDK 11, HttpClient replaces the legacy HttpURLConnection. It supports:</p><ul><li>HTTP/2</li><li>connection pooling</li><li>asynchronous requests</li><li>SSL/TLS</li><li>timeouts</li><li>a fluent API</li></ul><h3>Synchronous Example</h3><pre>HttpClient client = HttpClient.newHttpClient();<br>HttpRequest req = HttpRequest.newBuilder()<br>        .uri(URI.create(&quot;https://api.github.com&quot;))<br>        .build();<br>HttpResponse&lt;String&gt; res =<br>        client.send(req, HttpResponse.BodyHandlers.ofString());<br>System.out.println(res.statusCode());<br>System.out.println(res.body());</pre><h3>Asynchronous Example</h3><pre>client.sendAsync(req, HttpResponse.BodyHandlers.ofString())<br>      .thenApply(HttpResponse::body)<br>      .thenAccept(System.out::println)<br>      .join();</pre><p>Internally, HttpClient already uses non-blocking I/O and an event-driven architecture, which makes asynchronous requests highly efficient.</p><h3>Virtual Threads with HttpClient</h3><p>Virtual threads become especially useful when using the blocking send() API.</p><p>Instead of building complex asynchronous pipelines, you can write simple blocking code while still achieving high concurrency.</p><pre>ExecutorService executor =<br>        Executors.newVirtualThreadPerTaskExecutor();<br>HttpClient client = HttpClient.newBuilder()<br>        .connectTimeout(Duration.ofSeconds(5))<br>        .version(HttpClient.Version.HTTP_2)<br>        .build();<br>for (String uri : List.of(<br>        &quot;https://api.github.com&quot;,<br>        &quot;https://httpbin.org/get&quot;,<br>        &quot;https://openjdk.org&quot;)) {<br>    executor.submit(() -&gt; {<br>        try {<br>            HttpRequest request =<br>                    HttpRequest.newBuilder(URI.create(uri)).build();<br>            HttpResponse&lt;String&gt; response =<br>                    client.send(request,<br>                            HttpResponse.BodyHandlers.ofString());<br>            System.out.println(uri + &quot; -&gt; &quot; + response.statusCode());<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>    });<br>}</pre><p>Each request runs in its own virtual thread, which is extremely lightweight compared to traditional platform threads.</p><p>This allows thousands of concurrent blocking operations without exhausting system resources.</p><h3>Connection Pooling &amp; Tuning</h3><p>HttpClient automatically manages a connection pool and reuses TCP connections when possible. This reduces latency by avoiding repeated TLS handshakes and connection setup.</p><p>Example configuration:</p><pre>HttpClient client = HttpClient.newBuilder()<br>        .connectTimeout(Duration.ofSeconds(5))<br>        .followRedirects(HttpClient.Redirect.NORMAL)<br>        .version(HttpClient.Version.HTTP_2)<br>        .build();</pre><h3>Best Practices</h3><ul><li>Reuse a single shared HttpClient instance per application</li><li>Always define connection and request timeouts</li><li>Prefer HTTP/2 when calling the same host frequently</li><li>Perform load testing under realistic concurrency using tools like wrk, hey, or JMeter</li></ul><h3>Server + Client Together</h3><p>Because both the client and server can run on virtual threads, it is possible to build highly concurrent services using a straightforward blocking model.</p><p>Typical architecture:</p><pre>Client Request<br>     │<br>HttpServer (Virtual Threads)<br>     │<br>Business Logic<br>     │<br>HttpClient Calls<br>     │<br>External Services</pre><p>Virtual threads allow the server to process many concurrent requests while also making multiple downstream HTTP calls efficiently.</p><h3>Why It Matters</h3><p>Traditionally, scaling blocking I/O required either:</p><ul><li>Complex asynchronous code, or</li><li>Reactive frameworks</li></ul><p>Virtual threads change this tradeoff.</p><p>You can now write simple blocking logic while still supporting very high concurrency.</p><p>Benefits include:</p><ul><li>Simpler code</li><li>Easier debugging</li><li>Fewer synchronization issues</li><li>Predictable performance under load</li></ul><h3>Best Practices</h3><ul><li>Use Executors.newVirtualThreadPerTaskExecutor() for request handling</li><li>Reuse a shared HttpClient</li><li>Configure proper timeouts</li><li>Tune backlog values to handle connection bursts</li><li>Prefer HTTP/2 for service-to-service communication</li></ul><h3>Conclusion</h3><p>The combination of HttpClient, HttpServer, and Virtual Threads represents an important evolution in modern Java.</p><p>Developers can build highly concurrent services using only the standard JDK while keeping the programming model simple and maintainable.</p><p>Virtual threads bring back the clarity of blocking code while preserving the scalability traditionally associated with asynchronous frameworks.</p><p>Modern Java now provides a powerful and elegant foundation for building high-performance network applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8eed971ae84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside the Blackbox of Java GC: G1, ZGC, Heap & Performance Tuning]]></title>
            <link>https://medium.com/@ediznajim/inside-the-blackbox-of-java-gc-g1-zgc-heap-performance-tuning-0e4c57479087?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e4c57479087</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 21:02:03 GMT</pubDate>
            <atom:updated>2026-03-04T21:02:03.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXlSeDkwu_hivKJ6Lo11pA.png" /></figure><h3>Mastering Java GC: G1, ZGC, Heap Sizing, Allocation Rate &amp; Escape Analysis</h3><p>In modern Java (JDK 21+), understanding and tuning the Garbage Collector (GC) is key to building scalable, high-performance applications. Here are the essentials I focus on in practice G1GC, ZGC tuning, heap sizing, allocation rate monitoring, and escape analysis.</p><h3>🔹 G1GC vs. ZGC</h3><p>G1GC (Garbage-First GC)</p><ul><li>Default since Java 9.</li><li>Optimized for balanced throughput and predictable low-latency pauses.</li><li>Works well for medium to large heaps (multi-GB).</li><li>“Pause Young” events typically last a few milliseconds (workload-dependent).</li></ul><p>ZGC (Z Garbage Collector)</p><ul><li>Introduced in Java 11 (experimental), production-ready since Java 15.</li><li>Generational ZGC arrived in Java 21, improving throughput for short-lived objects.</li><li>Ultra-low pause times (often sub-ms to low-ms), even on very large heaps (100s GB–TB).</li><li>Ideal for latency-sensitive systems (trading, gaming backends, highly concurrent SaaS).</li></ul><p>When to use which?</p><ul><li>Start with G1GC for general-purpose server workloads.</li><li>Move to ZGC if you need tighter latencies or run very large heaps and GC shows up in tail percentiles.</li><li>Consider ZGC when your SLOs (Service Level Objectives) require strict latency targets (e.g., “99% of requests must complete &lt;50ms”), ZGC’s near real-time GC behavior ensures pauses don’t break these promises.</li></ul><h3>🔹 Heap Sizing</h3><p>The heap is your memory budget, size it from load tests, not guesses.</p><ul><li>-Xmx → maximum heap size</li><li>-Xms → initial heap size</li><li>In production, prefer -Xms == -Xmx to avoid mid-run resizing.</li></ul><p>Example</p><pre># G1 with fixed heap and GC logging<br>java -XX:+UseG1GC -Xms512m -Xmx512m -Xlog:gc* -jar app.jar<br># Generational ZGC with a larger heap<br>java -XX:+UseZGC -Xms2g -Xmx2g -Xlog:gc* -jar app.jar</pre><p>If the heap is too small, the JVM performs frequent garbage collections, increasing the risk of promotion failures and OutOfMemoryError. If the heap is too large, memory may be wasted and full GC cycles (especially with G1) can take longer to complete.</p><h3>🔹 Allocation Rate</h3><p>Allocation rate = how many bytes your app creates per second. High churn drives GC work and pause frequency.</p><p>How to measure</p><ul><li>GC logs: -Xlog:gc* (watch Young pause frequency/duration and promotions).</li><li>Java Flight Recorder (JFR): production-safe profiling of allocations and pauses.</li><li>Custom benchmarks / load tests to correlate allocations with latency.</li></ul><p>Example output</p><pre>Sec 1 | Allocated ~206 MB | GC runs=6 | GC time=103 ms | HeapUsed=210 MB<br>Sec 2 | Allocated ~210 MB | GC runs=6 | GC time=106 ms | HeapUsed=421 MB</pre><p>If heap usage climbs while objects are retained, you’ll see intensifying GC and potentially OOM. Reduce avoidable allocations (boxing, temp collections, string building) and reuse buffers where appropriate.</p><h3>Quick Tuning Checklist</h3><ol><li>Start with sane defaults</li><li>Measure under real load</li><li>Reduce allocation hot spots</li><li>Re-size the heap</li><li>Consider ZGC for strict SLOs / huge heaps</li><li>Re-measure after each change</li></ol><h3>Key Takeaways</h3><ul><li>G1GC (default since Java 9) is an excellent general-purpose collector.</li><li>ZGC (GenZGC in JDK 21) delivers ultra-low pauses at massive scale.</li><li>Heap sizing must come from load testing and live-set observation.</li><li>Allocation rate is the hidden driver of GC pressure, monitor and reduce churn.</li></ul><h3>Conclusion</h3><p>Garbage collection is not just a background process, it directly impacts your app’s performance, latency, and scalability. By understanding which GC to choose (G1 vs. ZGC), tuning heap sizing, monitoring allocation rates, and leveraging escape analysis, you can build systems that stay predictable even under heavy load.</p><p>Whether you’re running microservices, large SaaS platforms, or latency-sensitive systems, mastering GC behavior helps you deliver faster, more reliable, and cost-efficient Java applications.</p><p><strong>What GC are you running in production right now ? G1GC, ZGC, Shenandoah, or something else ?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e4c57479087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real API Gateway with Spring Cloud Gateway: Sessions, Security, JWT & Filters]]></title>
            <link>https://medium.com/@ediznajim/building-a-real-api-gateway-with-spring-cloud-gateway-sessions-security-jwt-filters-100a53357277?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/100a53357277</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 11:26:49 GMT</pubDate>
            <atom:updated>2026-02-23T11:26:49.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSAmLEIcF-i_Mrm_9_uLdw.png" /></figure><h3>Building a Real API Gateway with Spring Cloud Gateway: Sessions, Security, JWT &amp; Filters (Full Practical Guide)</h3><p>Gateway is not about simply forwarding requests. In real-world systems, an API Gateway is a critical security and control boundary that sits in front of all internal services.</p><p>A production-grade gateway is responsible for:</p><ul><li>Authenticating users</li><li>Managing sessions</li><li>Protecting against session hijacking</li><li>Enforcing rate limits</li><li>Handling CORS correctly</li><li>Logging and tracing requests</li><li>Normalizing errors into a consistent format</li><li>Propagating identity (JWT) to downstream services</li><li>Rejecting invalid or malicious requests before they reach internal systems</li></ul><p>This guide explains how to turn Spring Cloud Gateway into a real, security-aware API Gateway using a carefully designed sequence of custom Global Filters.</p><p>Minimize image</p><p>Edit image</p><p>Delete image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xk9BipsvT8QvdHKa" /></figure><p>All classes use:</p><pre>package com.enacademy.gateway;</pre><h3>What We Are Building</h3><p>Instead of this:</p><pre>Client → Microservices</pre><p>We build this:</p><pre>Client<br> ↓<br>[Spring Cloud Gateway]</pre><pre>1. Preflight CORS (OPTIONS)<br>2. CORS headers<br>3. Logging (request/response)<br>4. Rate limiting (Bucket4j)<br>5. Login handler (/login → session)<br>6. Logout handler<br>7. Session validation<br>8. Device security (IP + User-Agent)<br>9. Session TTL refresh<br>10. Internal JWT generation<br>11. Standard gateway headers<br>12. Error normalization (JSON)<br> ↓<br>Microservices (Order, Account, Report…)</pre><p>This is how real API gateways behave.</p><h3>Why Spring Cloud Gateway?</h3><p>Spring Cloud Gateway provides:</p><ul><li>High performance (Netty)</li><li>Reactive pipeline (Project Reactor)</li><li>Flexible routing DSL</li><li>Global filters for pre/post processing</li><li>Easy customization</li></ul><p>But SCG intentionally does <em>not</em> provide:</p><ul><li>Login flow</li><li>Session management</li><li>Identity propagation</li><li>Device binding</li><li>Structured JSON errors</li><li>Rate limiting</li><li>Authorization logic</li></ul><p>So we must add them ourselves.</p><p>This article shows you how and why.</p><h3>Route Configuration (start simple)</h3><pre>spring:<br>  cloud:<br>    gateway:<br>      routes:<br>        - id: order-service<br>          uri: http://localhost:9090<br>          predicates:<br>            - Path=/api/orders/**<br>          filters:<br>            - StripPrefix=1</pre><p>This is enough to start. Now we build the security around it.</p><h3>Filter 1 — Preflight CORS (OPTIONS)</h3><p>Browsers send OPTIONS before actual requests. If we don’t return early, login/session filters will break.</p><pre>@Component<br>public class PreflightCorsFilter implements GlobalFilter, Ordered {<br>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange exchange, GatewayFilterChain chain) {<br>        if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {<br>            exchange.getResponse().setStatusCode(HttpStatus.OK);<br>            return exchange.getResponse().setComplete();<br>        }<br>        return chain.filter(exchange);<br>    }<br>    @Override public int getOrder() { return -120; }<br>}</pre><h3>Filter 2 — CORS Configuration</h3><p>CORS must be global and consistent.</p><pre>@Configuration<br>public class CorsConfig {</pre><pre>    @Bean<br>    public CorsWebFilter corsWebFilter() {</pre><pre>        CorsConfiguration c = new CorsConfiguration();</pre><pre>        c.setAllowCredentials(true);<br>        c.addAllowedOriginPattern(&quot;*&quot;);<br>        c.addAllowedHeader(&quot;*&quot;);<br>        c.addAllowedMethod(&quot;*&quot;);</pre><pre>        c.addExposedHeader(&quot;X-Session-Id&quot;);<br>        c.addExposedHeader(&quot;X-Request-ID&quot;);<br>        c.addExposedHeader(&quot;X-Auth-Error&quot;);</pre><pre>        UrlBasedCorsConfigurationSource s = <br>              new UrlBasedCorsConfigurationSource();<br>        s.registerCorsConfiguration(&quot;/**&quot;, c);</pre><pre>        return new CorsWebFilter(s);<br>    }<br>}</pre><h3>Filter 3 — Logging (Tracing Every Request)</h3><p>You cannot secure what you cannot observe.</p><pre>@Component<br>public class LogFilter implements GlobalFilter, Ordered {<br>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        long start = System.currentTimeMillis();<br>        String path = ex.getRequest().getURI().getRawPath();</pre><pre>        return chain.filter(ex).doFinally(sig -&gt; {<br>            long time = System.currentTimeMillis() - start;</pre><pre>            System.out.printf(<br>                &quot;[Gateway] %s %s | Status=%s | Time=%d ms%n&quot;,<br>                ex.getRequest().getMethod(),<br>                path,<br>                ex.getResponse().getStatusCode(),<br>                time<br>            );<br>        });<br>    }<br>    @Override public int getOrder() { return -100; }<br>}</pre><h3>Filter 4 — Rate Limiting</h3><p>Protect the gateway first.</p><pre>@Component<br>public class InMemoryRateLimiterFilter implements GlobalFilter, Ordered {</pre><pre>    private final Map&lt;String, Bucket&gt; ipBuckets = new ConcurrentHashMap&lt;&gt;();</pre><pre>    private Bucket createBucket() {<br>        return Bucket4j.builder()<br>                .addLimit(Bandwidth.classic(50, Refill.intervally(50, Duration.ofSeconds(1))))<br>                .build();<br>    }</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        String ip = ex.getRequest().getRemoteAddress().getAddress().getHostAddress();<br>        Bucket bucket = ipBuckets.computeIfAbsent(ip, k -&gt; createBucket());</pre><pre>        if (bucket.tryConsume(1)) return chain.filter(ex);</pre><pre>        ex.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);<br>        return ex.getResponse().setComplete();<br>    }</pre><pre>    @Override public int getOrder() { return -95; }<br>}</pre><h3>Local Session Model</h3><p>We implement a minimal session object tied to IP + User-Agent.</p><pre>public class Session {<br>    private final String username;<br>    private long expireAt;<br>    private final String ip;<br>    private final String userAgent;</pre><pre>    public Session(String username, long expireAt, String ip, String userAgent) {<br>        this.username = username;<br>        this.expireAt = expireAt;<br>        this.ip = ip;<br>        this.userAgent = userAgent;<br>    }<br>}</pre><p>And a session store:</p><pre>@Component<br>public class SessionStore {<br>    private final Map&lt;String, Session&gt; sessions = new ConcurrentHashMap&lt;&gt;();<br>    private static final long TTL_MIN = 30;</pre><pre>    public String create(String user, String ip, String ua) {<br>        String id = UUID.randomUUID().toString();<br>        long exp = System.currentTimeMillis() + TTL_MIN * 60_000;<br>        sessions.put(id, new Session(user, exp, ip, ua));<br>        return id;<br>    }</pre><pre>    public boolean isValid(String id) {<br>        Session s = sessions.get(id);<br>        if (s == null) return false;<br>        if (System.currentTimeMillis() &gt; s.getExpireAt()) {<br>            sessions.remove(id);<br>            return false;<br>        }<br>        return true;<br>    }</pre><pre>    public void refresh(String id) {<br>        Session s = sessions.get(id);<br>        if (s != null) {<br>            s.setExpireAt(System.currentTimeMillis() + TTL_MIN * 60_000);<br>        }<br>    }</pre><pre>    public Session get(String id) { return sessions.get(id); }</pre><pre>    public void remove(String id) { sessions.remove(id); }<br>}</pre><h3>Filter 5 — Login Handler (POST /login)</h3><p>The gateway becomes the login endpoint.</p><pre>@Component<br>public class LoginPostFilter implements GlobalFilter, Ordered {</pre><pre>    private final SessionStore store;<br>    private final ObjectMapper mapper = new ObjectMapper();</pre><pre>    public LoginPostFilter(SessionStore store) {<br>        this.store = store;<br>    }</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        if (!ex.getRequest().getURI().getPath().equals(&quot;/login&quot;)<br>            || ex.getRequest().getMethod() != HttpMethod.POST)<br>            return chain.filter(ex);</pre><pre>        return DataBufferUtils.join(ex.getRequest().getBody())<br>            .flatMap(buf -&gt; {<br>                try {<br>                    String json = StandardCharsets.UTF_8.decode(buf.asByteBuffer()).toString();<br>                    LoginRequest req = mapper.readValue(json, LoginRequest.class);</pre><pre>                    if (isValidUser(req.username, req.password)) {</pre><pre>                        String ip = ex.getRequest().getRemoteAddress().getAddress().getHostAddress();<br>                        String ua = ex.getRequest().getHeaders().getFirst(&quot;User-Agent&quot;);</pre><pre>                        String sessionId = store.create(req.username, ip, ua);<br>                        ex.getResponse().setStatusCode(HttpStatus.OK);<br>                        ex.getResponse().getHeaders().add(&quot;X-Session-Id&quot;, sessionId);</pre><pre>                        return writeJson(ex, &quot;&quot;&quot;<br>                            {&quot;success&quot;: true, &quot;username&quot;: &quot;%s&quot;}<br>                            &quot;&quot;&quot;.formatted(req.username));<br>                    }</pre><pre>                    ex.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);<br>                    return ex.getResponse().setComplete();</pre><pre>                } catch (Exception e) {<br>                    ex.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);<br>                    return ex.getResponse().setComplete();<br>                }<br>            });<br>    }</pre><pre>    private boolean isValidUser(String u, String p) { return &quot;ediz&quot;.equals(u) &amp;&amp; &quot;1234&quot;.equals(p); }</pre><pre>    private Mono&lt;Void&gt; writeJson(ServerWebExchange ex, String json) {<br>        DataBuffer db = ex.getResponse().bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));<br>        return ex.getResponse().writeWith(Mono.just(db));<br>    }</pre><pre>    @Override public int getOrder() { return -85; }</pre><pre>    private static class LoginRequest {<br>        public String username;<br>        public String password;<br>    }<br>}</pre><h3>Filter 6 — Session Validation</h3><p>Everything except /login, /logout, and OPTIONS must have a session.</p><pre>@Component<br>public class SessionValidationFilter implements GlobalFilter, Ordered {</pre><pre>    private final SessionStore store;</pre><pre>    public SessionValidationFilter(SessionStore store) { this.store = store; }</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        String path = ex.getRequest().getURI().getPath();<br>        HttpMethod method = ex.getRequest().getMethod();</pre><pre>        if (path.equals(&quot;/login&quot;) || path.equals(&quot;/logout&quot;) || method == HttpMethod.OPTIONS)<br>            return chain.filter(ex);</pre><pre>        String sessionId = ex.getRequest().getHeaders().getFirst(&quot;X-Session-Id&quot;);</pre><pre>        if (sessionId == null || !store.isValid(sessionId))<br>            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, &quot;Invalid session&quot;);</pre><pre>        return chain.filter(ex);<br>    }</pre><pre>    @Override public int getOrder() { return -80; }<br>}</pre><h3>Filter 7 — Device Security</h3><p>Tie session to IP + User-Agent.</p><pre>@Component<br>public class DeviceSecurityFilter implements GlobalFilter, Ordered {</pre><pre>    private final SessionStore store;</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        String sessionId = ex.getRequest().getHeaders().getFirst(&quot;X-Session-Id&quot;);</pre><pre>        if (sessionId != null &amp;&amp; store.isValid(sessionId)) {<br>            Session s = store.get(sessionId);<br>            String ip = ex.getRequest().getRemoteAddress().getAddress().getHostAddress();<br>            String ua = ex.getRequest().getHeaders().getFirst(&quot;User-Agent&quot;);</pre><pre>            if (!s.getIp().equals(ip))<br>                throw new ResponseStatusException(HttpStatus.FORBIDDEN, &quot;IP mismatch&quot;);</pre><pre>            if (ua != null &amp;&amp; !ua.equals(s.getUserAgent()))<br>                throw new ResponseStatusException(HttpStatus.FORBIDDEN, &quot;Device mismatch&quot;);<br>        }</pre><pre>        return chain.filter(exchange);<br>    }</pre><pre>    @Override public int getOrder() { return -78; }<br>}</pre><h3>Filter 8 — Session Refresh (Sliding Expiration)</h3><pre>@Component<br>public class SessionRefreshFilter implements GlobalFilter, Ordered {</pre><pre>    private final SessionStore store;</pre><pre>    public SessionRefreshFilter(SessionStore store) { this.store = store; }</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        String sessionId = ex.getRequest().getHeaders().getFirst(&quot;X-Session-Id&quot;);</pre><pre>        if (sessionId != null &amp;&amp; store.isValid(sessionId)) {<br>            store.refresh(sessionId);<br>        }</pre><pre>        return chain.filter(ex);<br>    }</pre><pre>    @Override public int getOrder() { return -75; }<br>}</pre><h3>Filter 9 — Internal JWT Propagation</h3><p>Microservices should NOT deal with sessions. They receive a JWT generated by the gateway.</p><pre>@Component<br>public class JwtPropagationFilter implements GlobalFilter, Ordered {</pre><pre>    private final SessionStore store;<br>    private final JwtUtil jwt;</pre><pre>    public JwtPropagationFilter(SessionStore store, JwtUtil jwt) {<br>        this.store = store;<br>        this.jwt = jwt;<br>    }</pre><pre>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        String sessionId = ex.getRequest().getHeaders().getFirst(&quot;X-Session-Id&quot;);</pre><pre>        if (sessionId != null &amp;&amp; store.isValid(sessionId)) {</pre><pre>            Session s = store.get(sessionId);</pre><pre>            String token = jwt.create(Map.of(<br>                &quot;sub&quot;, s.getUsername(),<br>                &quot;ip&quot;, s.getIp(),<br>                &quot;device&quot;, s.getUserAgent(),<br>                &quot;sessionId&quot;, sessionId<br>            ));</pre><pre>            ex = ex.mutate().request(r -&gt;<br>                    r.header(&quot;X-Internal-JWT&quot;, token)<br>            ).build();<br>        }</pre><pre>        return chain.filter(ex);<br>    }</pre><pre>    @Override public int getOrder() { return -60; }<br>}</pre><p>Microservices decode it:</p><pre>String jwt = request.getHeader(&quot;X-Internal-JWT&quot;);<br>String username = jwtUtil.parse(jwt).get(&quot;sub&quot;, String.class);</pre><h3>Filter 10 — JSON Error Normalization</h3><p>Never return raw Spring errors.</p><pre>@Component<br>public class ExceptionNormalizationFilter implements GlobalFilter, Ordered {<br>    @Override<br>    public Mono&lt;Void&gt; filter(ServerWebExchange ex, GatewayFilterChain chain) {</pre><pre>        return chain.filter(ex)<br>            .onErrorResume(err -&gt; {</pre><pre>                HttpStatus st = HttpStatus.INTERNAL_SERVER_ERROR;<br>                String msg = &quot;Unexpected error&quot;;</pre><pre>                if (err instanceof ResponseStatusException rse) {<br>                    st = rse.getStatusCode();<br>                    msg = rse.getReason();<br>                }</pre><pre>                ex.getResponse().setStatusCode(st);<br>                ex.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);</pre><pre>                String json = &quot;&quot;&quot;<br>                {&quot;success&quot;:false, &quot;message&quot;:&quot;%s&quot;, &quot;status&quot;:%d}<br>                &quot;&quot;&quot;.formatted(msg, st.value());</pre><pre>                DataBuffer buffer = ex.getResponse().bufferFactory()<br>                        .wrap(json.getBytes(StandardCharsets.UTF_8));</pre><pre>                return ex.getResponse().writeWith(Mono.just(buffer));<br>            });<br>    }</pre><pre>    @Override public int getOrder() { return -50; }<br>}</pre><h3>Final Filter Pipeline (Summary)</h3><pre>-120  Preflight CORS<br>-110  CORS header injection<br>-100  Logging<br>-95   Rate limiting<br>-85   Login handler<br>-82   Logout handler<br>-80   Session validation<br>-78   Device security<br>-75   Session refresh<br>-70   Add headers<br>-60   JWT propagation<br>-50   Error normalization<br> → Routing to microservice</pre><h3>Why This Architecture Works</h3><ul><li>The gateway becomes the <em>security boundary</em></li><li>Microservices stay stateless</li><li>Internal JWT gives each service user identity</li><li>Session hijacking is prevented</li><li>The error format is consistent</li><li>The login flow is centralized</li><li>The rate limiter protects the entire cluster</li><li>CORS behaves correctly in browsers</li></ul><p>This model follows the same pattern as:</p><ul><li>AWS API Gateway</li><li>Kong</li><li>Apigee</li><li>Netflix Zuul 2</li></ul><p>but built with Spring Cloud Gateway + Java + small filters you understand.</p><h3>Final Words</h3><p>This architecture is the foundation of a serious, runnable gateway:</p><ul><li>Easy to debug</li><li>Easy to extend</li><li>Suitable for internal platforms</li><li>Teaches every critical concept in Gateway engineering</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=100a53357277" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye Complex Concurrency: Meet Java’s Virtual Threads & Structured Concurrency]]></title>
            <link>https://medium.com/@ediznajim/goodbye-complex-concurrency-meet-javas-virtual-threads-structured-concurrency-339ab45852b7?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/339ab45852b7</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 21:45:40 GMT</pubDate>
            <atom:updated>2026-02-17T21:45:40.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JFL67Mt5T5yhw7u3s11uQ.png" /></figure><h3>Java Virtual Threads and Structured Concurrency (Project Loom)</h3><p>Java has always had powerful concurrency tools, but building scalable and safe concurrent applications wasn’t easy. With Project Loom, Java introduces two groundbreaking features: Virtual Threads and Structured Concurrency. Let’s explore what they are, why they matter, and how they simplify concurrent programming.</p><h3>Virtual Threads: Lightweight Concurrency</h3><h3>When did they come?</h3><ul><li>Preview in Java 19 &amp; 20</li><li>Standard (final) in Java 21 (LTS, 2023)</li></ul><h3>The Problem with Platform Threads</h3><p>Traditional Java threads are mapped directly to OS threads. They are:</p><ul><li>Heavyweight → each consumes MBs of memory.</li><li>Limited → creating thousands can exhaust system resources.</li><li>Blocking → when a thread waits on I/O, its OS thread is stuck.</li></ul><h3>Enter Virtual Threads</h3><p>Virtual threads are lightweight threads managed by the JVM, not the OS:</p><ul><li>Creating millions is possible.</li><li>Blocking calls (Thread.sleep, JDBC queries, HTTP requests) are cheap → the JVM parks/unparks virtual threads without blocking OS threads.</li><li>Code looks synchronous and readable, but scales like asynchronous systems.</li></ul><h3>Example</h3><pre>// Platform thread<br>new Thread(() -&gt; fetchData()).start();<br>// Virtual thread (Java 21+)<br>Thread.startVirtualThread(() -&gt; fetchData());</pre><p>With virtual threads, you can assign one thread per task/request without worrying about scalability.</p><h3>Structured Concurrency: Safer Task Management</h3><h3>When did it come?</h3><ul><li>Introduced as preview in Java 21 (2023)</li><li>Still preview in Java 22 → 25 (APIs evolving)</li></ul><h3>The Problem with Unstructured Concurrency</h3><p>Traditional concurrency often looks like this:</p><pre>Future&lt;User&gt; user = executor.submit(() -&gt; fetchUser());<br>Future&lt;Order&gt; orders = executor.submit(() -&gt; fetchOrders());</pre><p>Problems:</p><ul><li>Who owns these tasks? If the method returns early, tasks may leak.</li><li>Error handling is messy. One task can fail while others keep running.</li><li>Manual cleanup. You must cancel futures and shut down executors yourself.</li></ul><h3>Structured Concurrency to the Rescue</h3><p>Structured concurrency enforces the idea that:</p><blockquote>“Tasks should live only as long as the scope that created them.”</blockquote><p>In Java, this is supported via StructuredTaskScope. A scope:</p><ul><li>Runs multiple tasks concurrently.</li><li>Waits for them to complete before exiting.</li><li>Cancels siblings automatically on failure (depending on policy).</li></ul><h3>Example: ShutdownOnFailure</h3><pre>try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>    var userTask  = scope.fork(() -&gt; fetchUser());<br>    var orderTask = scope.fork(() -&gt; fetchOrders());<br>    scope.join();          // wait for all<br>    scope.throwIfFailed(); // rethrow first failure<br>    System.out.println(userTask.get() + &quot; &quot; + orderTask.get());<br>}</pre><p>Benefits:</p><ul><li>If any task fails → others are cancelled.</li><li>No orphaned threads.</li><li>Clean, predictable error handling.</li></ul><h3>Example: ShutdownOnSuccess</h3><pre>try (var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;String&gt;()) {<br>    scope.fork(() -&gt; fetchFromMirror1());<br>    scope.fork(() -&gt; fetchFromMirror2());<br>    scope.fork(() -&gt; fetchFromMirror3());<br>    scope.join();<br>    String result = scope.result(); // first successful result<br>    System.out.println(&quot;Winner: &quot; + result);<br>}</pre><p>Here, as soon as one task succeeds, the rest are cancelled. Perfect for querying multiple redundant services.</p><h3>Why This Matters</h3><p>Together, Virtual Threads and Structured Concurrency make concurrent programming in Java:</p><ul><li>Scalable → millions of lightweight tasks.</li><li>Readable → synchronous style, no callback hell.</li><li>Safe → no orphaned tasks, automatic cancellation, simpler error handling.</li><li>Compatible → works with existing blocking APIs (JDBC, sockets, etc).</li></ul><h3>Conclusion</h3><p>Project Loom changes how we think about concurrency in Java:</p><ul><li>Virtual Threads → came in Java 21 (LTS) and are now standard.</li><li>Structured Concurrency → introduced as preview in Java 21, still evolving in later releases.</li></ul><p>The result: You can now write simple, synchronous-looking code that scales to thousands or millions of concurrent tasks, without giving up safety or maintainability.</p><p>Have you tried Virtual Threads or Structured Concurrency in your Java projects yet?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339ab45852b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Soft vs Hard Timeouts: An Architectural Decision]]></title>
            <link>https://medium.com/@ediznajim/soft-vs-hard-timeouts-an-architectural-decision-c63291750e59?source=rss-660c8f63dea9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63291750e59</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Ediz NAJIM]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 06:01:59 GMT</pubDate>
            <atom:updated>2026-02-16T06:01:59.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rAatrxoUIxudRgqjJwSRw.png" /></figure><p>Soft vs hard timeouts are not mere implementation details. They define how a system behaves under failure, making them an architectural decision, not a configuration parameter.</p><p>At the architectural level, the question is not: <em>“How long should we wait?”</em></p><p>The real question is: <em>“What is allowed to continue after a deadline?”</em></p><h3>Soft Timeout</h3><p>A soft timeout occurs when the caller stops waiting for an operation after a time limit, but the operation itself continues running in the background.</p><p>The timeout affects <em>who is waiting</em>, not <em>what is running</em>.</p><p>In simple terms, a soft timeout means: <em>“I no longer care about the result.”</em> not <em>“Stop the work.”</em></p><p>Even after the timeout:</p><ul><li>Execution may complete successfully</li><li>It may partially complete</li><li>Side effects may still occur</li></ul><p>All while the caller has already moved on or returned an error.</p><h3>Key characteristics of a soft timeout</h3><ul><li>Execution is not cancelled</li><li>Background work continues</li><li>Side effects may still occur</li></ul><p>This is the default behavior in many APIs and frameworks.</p><h3>Where to Use Soft Timeout Architecture (and Why)</h3><p>A soft-timeout architecture is appropriate when progress matters more than immediate certainty or strict correctness.</p><p>Here, time limits apply only at the caller boundary. If the caller times out, the work is still allowed to continue in the background.</p><p>Use soft timeouts when:</p><ul><li>The operation is best-effort</li><li>Late completion is acceptable</li><li>Results can be retried or reconciled</li><li>Side effects are idempotent or reversible</li></ul><p>Typical use cases:</p><ul><li>Asynchronous messaging</li><li>Retry-based APIs</li><li>Notifications and emails</li><li>Data enrichment pipelines</li><li>Non-critical background processing</li></ul><p>Benefits of soft timeouts:</p><ul><li>Higher system liveness</li><li>Better tolerance to slow dependencies</li><li>Fewer blocked threads</li><li>Natural fit for async and event-driven flows</li></ul><p>Trade-offs (the hidden cost):</p><p>Because work continues after the timeout, the architecture must handle:</p><ul><li>Idempotency</li><li>Deduplication</li><li>Compensation logic</li><li>Eventual consistency</li></ul><p>In other words:</p><p><em>Soft timeouts push complexity outward into retries, reconciliation, and cleanup.</em></p><p>Failures are not final, they are eventual.</p><h3>Hard Timeout</h3><p>A hard timeout occurs when the timeout actively terminates or cancels the execution once the time limit is reached. Here, the timeout affects the execution itself, not just the caller.</p><p>The system explicitly enforces: <em>“This operation must not continue beyond this deadline.”</em></p><p>Execution is stopped, forcefully or cooperatively, preventing any further progress beyond the deadline.</p><h3>Key characteristics of a hard timeout</h3><ul><li>Execution is cancelled or interrupted</li><li>Background work does not continue</li><li>Side effects are prevented after the timeout</li><li>Requires explicit design and cancellation awareness</li></ul><h3>One-sentence contrast</h3><p><em>A soft timeout stops waiting but lets work continue.</em> <em>A hard timeout stops the work itself.</em></p><h3>Where to Use Hard Timeout Architecture (and Why)</h3><p>A hard-timeout architecture is required when late execution is more dangerous than no execution.</p><p>Here, deadlines are part of the execution contract. Once the time boundary is reached, the system refuses to continue.</p><p>Use hard timeouts when:</p><ul><li>The operation changes critical state</li><li>Late side effects are unacceptable</li><li>Partial execution is dangerous or irreversible</li><li>The system must remain predictable under failure</li></ul><p>Typical use cases:</p><ul><li>Payments and transfers</li><li>Compliance checks</li><li>Trading and order matching</li><li>Risk evaluation</li><li>Account or balance mutations</li><li>Security-sensitive workflows</li></ul><p>Benefits of hard timeouts:</p><ul><li>Strong correctness guarantees</li><li>Predictable system behavior</li><li>Bounded execution</li><li>Reduced systemic risk</li><li>No “ghost” side effects after failure</li></ul><h3>Architectural impact</h3><p>Hard timeouts require:</p><ul><li>Deadline propagation across layers</li><li>Cancellation as a first-class signal</li><li>Interruptible and cooperative operations</li></ul><p>But in return:</p><p><em>Hard timeouts pull correctness inward and simplify the system’s safety model.</em></p><p>Late side effects become structurally impossible.</p><h3>Choosing Between Them (Rule of Thumb)</h3><p>If an operation can safely complete later → Soft timeout</p><p>If an operation must not complete late → Hard timeout</p><p>Or even simpler: <em>Soft timeouts belong at the edges.</em> <em>Hard timeouts belong at the core.</em></p><h3>How Timeouts Behave in Code</h3><h3>Soft Timeout in Java (Common, Default, Often Misunderstood)</h3><p>Future.get(timeout)</p><pre>ExecutorService executor = Executors.newSingleThreadExecutor();<br><br>Future&lt;String&gt; future = executor.submit(() -&gt; {<br>    Thread.sleep(5000); // long work<br>    return &quot;DONE&quot;;<br>});<br><br>try {<br>    // Soft timeout: waits only 2 seconds<br>    String result = future.get(2, TimeUnit.SECONDS);<br>} catch (TimeoutException e) {<br>    System.out.println(&quot;Timed out&quot;);<br>}</pre><p>What actually happens:</p><ul><li>The caller stops waiting after 2 seconds</li><li>The task keeps running</li><li>No cancellation happens</li></ul><p>This is a soft timeout because only the wait timed out, not the work.</p><p>CompletableFuture.orTimeout()</p><pre>CompletableFuture.runAsync(() -&gt; {<br>    sleep(5000);<br>    System.out.println(&quot;Still running!&quot;);<br>}).orTimeout(2, TimeUnit.SECONDS)<br> .exceptionally(ex -&gt; {<br>     System.out.println(&quot;Timed out&quot;);<br>     return null;<br> });</pre><p>Same behavior:</p><ul><li>The future completes exceptionally</li><li>The underlying task continues running</li></ul><p>orTimeout() times out the future, not the execution. This is dangerous for side-effecting operations unless you also wire cancellation explicitly (e.g., by cancelling the underlying task).</p><h3>Soft Timeout (Timeout + Cancellation)</h3><p>A hard timeout is not just waiting less. It is waiting less <em>and</em> cancelling execution.</p><p>Future.cancel(true)</p><pre>ExecutorService executor = Executors.newSingleThreadExecutor();<br><br>Future&lt;?&gt; future = executor.submit(() -&gt; {<br>    while (true) {<br>        if (Thread.currentThread().isInterrupted()) {<br>            System.out.println(&quot;Interrupted, stopping&quot;);<br>            return;<br>        }<br>        doWork();<br>    }<br>});<br><br>try {<br>    future.get(2, TimeUnit.SECONDS);<br>} catch (TimeoutException e) {<br>    future.cancel(true); // HARD TIMEOUT<br>}</pre><p>What happens:</p><ul><li>The caller times out</li><li>The execution is interrupted</li><li>The task stops if it cooperates</li></ul><p>This is a hard timeout.</p><h3>Hard Timeout with a Flag</h3><p><em>(Cleanest for Bounded Sequences)</em></p><p>This approach implements a hard timeout using a cancellation flag for a bounded sequence of operations. A shared CancelToken acts as a timeout signal. When the timeout expires, the token is marked as cancelled.</p><p>Before starting each operation, execution checks this token. If the token is cancelled, execution stops before the next operation begins. Already-running operations continue unless they also check the token internally.</p><p>Key guarantee: Once the timeout is reached, no new operation can start.</p><p>That is what makes this a hard timeout.</p><p>1) Cancellation flag</p><pre>import java.util.concurrent.atomic.AtomicBoolean;<br><br>public class CancelToken {<br>    private final AtomicBoolean cancelled = new AtomicBoolean(false);<br>    public void cancel() { cancelled.set(true); }<br>    public boolean isCancelled() { return cancelled.get(); }<br>    public void check() {<br>        if (isCancelled()) throw new RuntimeException(&quot;Hard timeout&quot;);<br>    }<br>}</pre><p>2) Run a bounded sequence of operations</p><pre>import java.util.List;<br><br>public class Runner {<br>    public static void run(List&lt;Runnable&gt; ops, CancelToken token) {<br>        for (Runnable op : ops) {<br>            token.check();   // stop BEFORE starting next operation<br>            op.run();<br>        }<br>    }<br>}</pre><p>3) Enforce the hard timeout</p><pre>import java.util.List;<br>import java.util.concurrent.*;<br><br>public class Demo {<br>    public static void main(String[] args) {<br>        CancelToken token = new CancelToken();<br>        List&lt;Runnable&gt; ops = List.of(<br>            () -&gt; sleep(700),<br>            () -&gt; sleep(700),<br>            () -&gt; sleep(700)<br>        );<br>        ScheduledExecutorService scheduler =<br>            Executors.newSingleThreadScheduledExecutor();<br>        scheduler.schedule(token::cancel, 2, TimeUnit.SECONDS);<br>        try {<br>            Runner.run(ops, token);<br>            System.out.println(&quot;All operations completed&quot;);<br>        } catch (RuntimeException e) {<br>            System.out.println(&quot;Stopped: &quot; + e.getMessage());<br>        } finally {<br>            scheduler.shutdownNow();<br>        }<br>    }<br>    static void sleep(long ms) {<br>        try { Thread.sleep(ms); }<br>        catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><p>What this guarantees:</p><ul><li>After 2 seconds, the flag flips to cancelled</li><li>No new operation starts after the deadline</li><li>If an operation is already running, it will finish unless it also checks the token</li></ul><h3>Final Takeaway</h3><p>Most systems think they have timeouts. In reality, they only stop waiting, while the work keeps running.</p><p>Timeouts are soft by default. Hard timeouts must be designed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63291750e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>