DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Integration

Integration refers to the process of combining software parts (or subsystems) into one system. An integration framework is a lightweight utility that provides libraries and standardized methods to coordinate messaging among different technologies. As software connects the world in increasingly more complex ways, integration makes it all possible facilitating app-to-app communication. Learn more about this necessity for modern software development by keeping a pulse on the industry topics such as integrated development environments, API best practices, service-oriented architecture, enterprise service buses, communication architectures, integration testing, and more.

icon
Latest Premium Content
Trend Report
Modern API Management
Modern API Management
Refcard #303
API Integration Patterns
API Integration Patterns
Refcard #249
GraphQL Essentials
GraphQL Essentials

DZone's Featured Integration Resources

Securing AI Agents in Production: A Developer’s Guide To Prompt Injection, RAG Leaks, and Tool Abuse

Securing AI Agents in Production: A Developer’s Guide To Prompt Injection, RAG Leaks, and Tool Abuse

By Paresh Sagar
Most teams ship their first AI agent the way they ship any feature: build it, test the happy path, add logging, deploy. Then the agent gets a CRM connection, a refund API, and read access to the internal wiki. Nobody calls it a security decision, but it is one. The trouble is that agents break a few assumptions we’ve relied on for years. A traditional service executes code you wrote. An agent interprets text you didn’t write, decides what to do, and calls tools on your behalf. That text can come from a customer, a PDF, a web page, or a retrieved document, and the model can’t reliably tell instructions from data. This article covers the failure modes I’d worry about first, and the engineering controls that address them, with some code you can adapt. Why Your Existing Security Stack Has Blind Spots A WAF sees a normal HTTPS request to a model API. A DLP tool sees encrypted traffic. Your API gateway sees an authenticated service account calling an endpoint it’s allowed to call. None of them see the part that matters: a user’s hidden instruction convinced the agent to call that endpoint. The gap is also growing quickly. Gartner has predicted that by 2028, half of enterprise incident response efforts will involve custom-built AI applications. That means the on-call engineer will increasingly be asked questions like “what did the agent retrieve, and which tool call did it make?” If your logs can’t answer that, the incident review will be painful. Visibility is the other half. A Cloud Security Alliance study commissioned by Zenity found that a majority of surveyed organizations had between 1 and 100 unsanctioned AI agents, and roughly half reported agents exceeding their intended permissions. You can’t apply controls to agents you don’t know exist, which is why I treat inventory as the first engineering task, not an audit afterthought. The same ground (shadow AI, runtime enforcement, posture management) is mapped across a full program in this enterprise AI security overview, so I’ll focus here on what you can implement at the application layer. Four Failure Modes Worth Designing Against The OWASP Top 10 for LLM Applications is a good checklist. In practice, four problems come up most. 1. Prompt Injection (Direct and Indirect) Direct injection is the obvious one: a user types “ignore your instructions.” Indirect injection is nastier. The malicious instruction is hidden in content the agent fetches: an email, a support ticket, a web page, a file. Two things follow from that. First, never treat retrieved content as trusted, even if it comes from your own systems, because someone upstream may have written it. Second, don’t rely on the prompt to enforce security. “You must never reveal the system prompt” is a request, not a control. 2. Tool Misuse and Agent Hijacking The risk jumps when an agent can act. The attack doesn’t need to steal data. It just needs to nudge the agent into a harmful action, sometimes gradually over several turns, where no single message looks like a violation. The fix is to enforce permissions in code, outside the model, at the point where a tool call happens. 3. RAG Leaks and Poisoning Retrieval systems rank by semantic relevance, not by who’s asking. If your vector store holds documents with different sensitivity levels and you don’t filter by the caller’s permissions, the most relevant chunk wins, including the confidential one. Poisoning is the mirror problem: bad content gets into the index, and the model treats it as ground truth. This gets harder to control when agentic RAG lets the agent decide what to retrieve and when, because the number of retrieval decisions per task goes up. 4. Supply Chain Drift Your agent depends on a model version, libraries, plugins, and often third-party MCP servers. Any of them can change behavior without a change in your repo. A tool server updating its responses is, from your agent’s point of view, new untrusted input. Controls You Can Actually Write Put Authorization in the Tool Layer, Not the Prompt The pattern I’d start with is a policy gate that every tool call passes through. The key detail is that authorization is evaluated against the end user’s identity and the tool’s policy, not whatever the agent decides it’s allowed to do. Python from dataclasses import dataclass, field from datetime import datetime, timezone @dataclass(frozen=True) class ToolPolicy: allowed_roles: frozenset max_amount: float | None = None requires_approval: bool = False POLICIES = { "search_kb": ToolPolicy(frozenset({"support", "admin"})), "issue_refund": ToolPolicy( frozenset({"admin"}), max_amount=100.0, requires_approval=True ), # Deliberately not callable by any agent "update_payment_details": ToolPolicy(frozenset()), } def authorize_tool_call(user_role: str, tool: str, args: dict, audit: list) -> str: policy = POLICIES.get(tool) decision, reason = "deny", "unknown tool" if policy: if user_role not in policy.allowed_roles: reason = "role not permitted" elif policy.max_amount is not None and args.get("amount", 0) > policy.max_amount: reason = "amount exceeds limit" elif policy.requires_approval: decision, reason = "needs_approval", "human approval required" else: decision, reason = "allow", "ok" audit.append({ "ts": datetime.now(timezone.utc).isoformat(), "tool": tool, "args": args, "role": user_role, "decision": decision, "reason": reason, }) return decision A few things worth noting: unknown tools are denied by default; high-impact tools can be made structurally unreachable (see update_payment_details), which neatly defeats the “gradually persuade the agent” attack, because no amount of persuasion changes the policy; and every decision, allowed or not, lands in an audit trail. Filter Retrieval by the Caller’s Permissions Apply access control before ranking, not after generation. The exact filter syntax varies by vector database, but the shape is the same: Python def retrieve(query: str, user, vector_store, k: int = 5): # Enforce document-level ACLs at query time, using metadata # written at ingestion (e.g., allowed_groups per chunk). return vector_store.search( query=query, k=k, filter={"allowed_groups": {"$in": list(user.groups)}, ) This only works if your ingestion pipeline stamps every chunk with its source permissions. If you retrofit that later, you’ll be re-indexing everything, so it’s cheaper to do it first. Treat Model Output as Untrusted Input If the model’s output feeds a SQL query, a shell command, or an HTML page, validate and encode it exactly as you would user input. Structured outputs with strict schema validation help here: reject anything that doesn’t parse, rather than trying to “fix” it. Log the Whole Decision Chain For each agent run, capture the user prompt, the retrieved chunks (and their sources), each tool call with arguments, and each policy decision. Without that chain, “why did the agent do this?” has no answer. With it, an incident becomes a replayable trace. Test Adversarially, and Keep Testing Add a set of injection and abuse cases to CI: hidden instructions in documents, multi-turn goal drift, requests that probe for the system prompt, attempts to reach tools outside the user’s role. Models, prompts, and tools change, so a test that passed last quarter proves little today. The most dangerous failure here isn’t a single bad response. It’s intent drift, where every step looks compliant, but the sequence ends somewhere nobody intended. Governance and Security Aren’t the Same Thing It’s tempting to assume a governance document covers all this. It doesn’t. Governance defines who owns the risk, which systems are approved, and what data is allowed. Security is the set of controls that enforce those decisions at runtime. NIST’s AI Risk Management Framework is a good structure for the first part, and teams that want a practical view of the policy side can look at how AI governance for enterprise AI maps to technical enforcement. The point is that a policy nobody enforces is just documentation, and controls without policy tend to end up inconsistent across teams. Build It in Early Retrofitting is the expensive path. Permissions models, retrieval ACLs, and audit logging are much easier to design when you’re building the AI agent than to bolt on after it’s wired into production systems. The same applies to how agents connect to the rest of your stack: every new AI integration adds a trust boundary that deserves a threat-modeling pass before it ships. More
Using Middleware in LangChain: Recovering From Tool Failures

Using Middleware in LangChain: Recovering From Tool Failures

By Ruchi Saini
In this article, we will look at how to handle tool errors using middleware in LangChain. Introduction Agents are built with tools that they can use to perform different tasks. The agent communicates with the LLM, and the LLM decides which tool to call based on the user's request. The agent then executes the selected tool and sends the tool result back to the LLM. The LLM can then decide whether another action or tool call is required. When an agent executes a tool, the tool may fail due to reasons such as a network error, an invalid input, or an external service being temporarily unavailable. Such failures can interrupt an otherwise successful agent workflow. We want to handle tool failures appropriately so that they do not unnecessarily interrupt the agent's workflow. In this article, we will learn how to use middleware to handle tool failures. What Is Middleware in LangChain? The core agent loop involves calling the model, deciding which tools to use, executing those tools, and continuing the loop until no more tool calls are needed. Middleware provides hooks that allow you to run custom logic before and after different steps in the agent loop. Middleware is code that runs between different parts of the agent's execution pipeline. It can modify or inspect the request before it reaches the model or a tool. It can also modify or inspect the response after the model or tool has finished executing. Pre-Built and Custom Middleware In LangChain, middleware can be broadly divided into two types: 1. Pre-built middleware – Ready-to-use middleware provided by LangChain for common use cases. LangChain provides pre-built middleware for several common scenarios. We can create an instance of the required middleware and attach it to the agent. The underlying logic is already implemented, so we do not need to write it ourselves. 2. Custom middleware – Middleware that we write to add our own logic and customize the agent's behavior. With custom middleware, we can add our own logic using hooks such as @before_model, @after_model, @before_tool, and @wrap_tool_call. Alternatively, we can create a custom middleware class by extending AgentMiddleware and overriding methods such as before_agent and after_agent. Two Ways to Handle Tool Errors In this article, we will look at two ways to handle tool errors: Using pre-built middleware – ToolRetryMiddlewareUsing @wrap_tool_call Pre-Built Middleware: ToolRetryMiddleware We will start with ToolRetryMiddleware. When a tool throws an exception, ToolRetryMiddleware can automatically retry the tool call. You can configure the middleware to wait for some time between attempts and specify the maximum number of retries. Retrying makes sense for temporary failures, such as network errors or temporary service unavailability, so the next attempt may succeed. But retries do not help with errors caused by invalid input or incorrect tool arguments. In such cases, ToolRetryMiddleware is not an appropriate choice. Let’s take a look at an example. Tool Let’s start by creating a tool called get_news that communicates with a free news API to retrieve news. Create a notebook in VS Code and add the following code. Python import requests from langchain.tools import tool attempts = 0 @tool def get_news(news_type: str) -> str: """Get one recent news article.""" global attempts attempts += 1 print(f"Attempt {attempts} to fetch {news_type} news.") if attempts <= 2: raise RuntimeError("Unable to get news at the moment. Please try again") response = requests.get( "https://freenewsapi.ai/v1/search", params={"q": news_type, "size": 1} ) return response.json()["results"][0]["title"] We will simulate an error while retrieving the news. This could be due to a temporary network problem, API failure, or service unavailability. To simulate this, we will make the tool raise a NetworkError on the first two attempts. We will also print “Attempt to fetch news” along with the attempt number each time the tool is called. As the tool is retried, you will see this message multiple times. The first two attempts will fail. The third attempt will succeed and return the expected response. ToolRetryMiddleware Next, we will create an instance of ToolRetryMiddleware provided by LangChain. Python from langchain.agents.middleware import ToolRetryMiddleware toolRetryMiddleware= ToolRetryMiddleware(max_retries=3,initial_delay=0.5, backoff_factor=2,retry_on=(RuntimeError),on_failure="error" ) Here, we are creating an instance of ToolRetryMiddleware. Let’s look at its configuration. The max_retries parameter is set to 3. This means the middleware will retry the tool up to 3 times before giving up. The initial_delay parameter specifies how long to wait before the first retry. Here, it is set to 0.5 seconds, so the middleware waits for 0.5 seconds before the first retry. Next, we have the backoff_factor, which is used to increase the delay between retries. The delay for each retry is calculated using: initial_delay * (backoff_factor ** retry_number) For the second retry, the calculation is: 0.5 * (2 ** 2) = 2 seconds So, the middleware waits for 2 seconds before the second retry. If the tool fails again, the delay for the third retry is: 0.5 * (2 ** 3) = 4 seconds Notice that the retry_number changes with each retry. Next is the retry_on parameter; it takes a tuple of exceptions for which the middleware should retry the tool. Finally, the on_failure parameter determines what happens when all retries are exhausted. It can be set to continue or error. Here, it is set to error, so an error is raised after the retries are exhausted. Create Agent We add OPENAI_API_KEY in the .env file in our folder and load this environment variable using the load_dotenv() function. Next, we create an agent using the model of our choice, the get_news tool we created, and the ToolRetryMiddleware. Python from langchain.agents import create_agent from langchain_openai import ChatOpenAI from dotenv import load_dotenv load_dotenv() myagent = create_agent( model=ChatOpenAI(model="gpt-4.1-mini"), tools=[get_news], middleware=[toolRetryMiddleware], system_prompt="First check if tool can handle the request." \ "If there is no tool defined for the request then only respond yourself" ) Invoke Agent Now we invoke the agent with a request to get cricket news. Python result = myagent.invoke({ "messages": [{ "role": "user", "content": "Give me cricket sports news." }] }) print(result['messages'][-1].content) We will get a response similar to this: As expected, the agent calls the tool three times. You can see the “Attempt to fetch news” message three times. On the third attempt, the tool execution succeeds, and the agent receives the response. Configuring ToolRetryMiddleware is helpful because our tools often call external services, which can sometimes fail temporarily. Retrying the tool call can help in such situations. @Wrap_tool_call Now let’s look at a scenario where we may want to log an error, add custom recovery logic, or return a message when a tool fails. This approach is useful when we want to handle errors in a customized way. We can handle exceptions directly inside the tool using a try-except block, or we can use @wrap_tool_call middleware. The middleware approach can be applied to one or more tools. For this article, we will keep the example focused on a single tool. With @wrap_tool_call middleware, we can wrap tool execution in our own error-handling logic. We can use a try-except block around the tool call. If the tool executes successfully, we return its output. If an exception occurs, we catch it and return an appropriate error message instead of allowing the exception to interrupt the agent's workflow. Tool Let’s create a tool that can send an email. For this article, the tool will simulate sending an email. Python from langchain.tools import tool import re @tool def send_email(emailId: str) -> bool: """Send an email to the specified email address.""" pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$" is_valid_email = bool(re.match(pattern, emailId)) if not is_valid_email: raise ValueError(f"Invalid email address: {emailId}") print("Sent email to", emailId) return True print("Tool Created") The tool first checks whether the email address is valid. If the address is invalid, it raises an error. If the address is valid, it prints a message indicating that the email was sent. Middleware Now, let’s create a function and decorate it with @wrap_tool_call. Python from langchain.agents.middleware import wrap_tool_call from langchain.messages import ToolMessage # Create error handling middleware @wrap_tool_call def handle_tool_errors(request, handler): """Handle tool execution errors with custom messages.""" print("Middleware : Checking for errors in tool...") try: return handler(request) except Exception as e: print("Error Caught in Middleware ***") return ToolMessage( content=f"Tool error: An unexpected error occurred. Please check your input and try again. ({str(e)})", tool_call_id=request.tool_call["id"] ) print("Error handling middleware created!") This function takes request and handler as arguments. The handler is responsible for executing the tool. When we call handler(request), the request is passed to the handler, which then executes the tool. Notice that the try-except block surrounds handler(request). This means that the tool execution is wrapped inside the try block, allowing the middleware to catch any exception raised during tool execution. This middleware currently catches the broad Exception type, but we can modify it to catch specific exceptions, such as ValueError or ZeroDivisionError. We can also add custom handling logic for different types of exceptions, if required. Create Agent Now, let’s create the agent using the model of our choice, the send_email tool, and the middleware that handles tool errors. Python from langchain.agents import create_agent from dotenv import load_dotenv from langchain_openai import ChatOpenAI from dotenv import load_dotenv load_dotenv() # Create agent with error handling error_handling_agent = create_agent( model=ChatOpenAI(model="gpt-4.1-mini"), tools=[send_email], middleware=[handle_tool_errors], system_prompt=( "For any email request, use send_email tool. " \ "Dont ask any further questions or perform any validation. " "The send_email tool is responsible for validation and sending email" ) ) print("Agent Created") Invoke Agent Now we invoke the agent with an invalid email address. Python from IPython.display import Markdown # Test the basic agent result = error_handling_agent.invoke({ "messages": [ {"role": "user", "content": "send email to ruchi@gmail" }] }) Markdown(result['messages'][-1].content) You will see a response similar to this: First, the middleware is called, which forwards the request to the tool. As the tool raised an error, the middleware catches the error, and the user receives a clear and helpful response instead of an unhandled exception. Complete Response We can also print the complete response. Python # Print the response from rich.pretty import pprint pprint(result, expand_all=True) In the printed result, you will find a UserMessage, an AIMessage, and a ToolMessage. In the AIMessage, you will find the tool call that instructs the agent to execute the tool. AIMessage: tool_calls=[{'name': 'send_email', 'args': {'emailId': 'ruchi@gmail'}] In the ToolMessage, you will find the error message returned by the middleware. ToolMessage: Tool error: An unexpected error occurred. Please check your input and try again. (Invalid email address: ruchi@gmail) The middleware catches the error and returns a ToolMessage from the except block. This message is then passed to the LLM. The LLM uses the ToolMessage to generate a response explaining that the email address is incomplete or invalid and asking the user to provide a valid email address. Conclusion Middleware allows us to handle tool failures in a graceful way. We can use ToolRetryMiddleware when retrying the tool may help it succeed. We can use @wrap_tool_call when we want to handle tool errors with our own logic. However, handling tool failures is just one use case of middleware. Middleware can be used in many other situations to customize and control different stages of an agent’s execution. More
The Rise of the Unsanctioned Agent Swarm
The Rise of the Unsanctioned Agent Swarm
By Nikita Kothari
Choosing a BBD Framework
Choosing a BBD Framework
By Himanshu Mandhyan
Persisting Cookies Across JAX-WS Service Calls Using a Custom SOAP Handler
Persisting Cookies Across JAX-WS Service Calls Using a Custom SOAP Handler
By Vishal Rameshchandra Shah
GET, POST, PUT, DELETE: Choosing HTTP Verbs in a Real .NET Core Web API, Not Just by the Textbook
GET, POST, PUT, DELETE: Choosing HTTP Verbs in a Real .NET Core Web API, Not Just by the Textbook

Most explanations of HTTP verbs in ASP.NET Core Web API stop at the dictionary definition: GET reads, POST creates, PUT updates, DELETE removes. That's true, but it doesn't explain why real enterprise APIs often bend these rules — and understanding why matters more in practice than reciting the definitions. This article walks through HTTP verb selection using a real HR/Payroll workflow scenario: submitting, updating, and removing leave requests. The Textbook Mapping In a typical Web API controller, the four core verbs map to CRUD operations like this: C# [ApiController] [Route("api/[controller]")] public class LeaveRequestController : ControllerBase { [HttpGet("get-emp-details")] public IActionResult GetEmployeeDetails(int finSlno, string empId, int createdBy) { // fetch and return data return Ok(employeeDetails); } [HttpPost("save-leave-request")] public IActionResult SaveLeaveRequest([FromBody] LeaveRequestDto request) { // create a new record return Ok(result); } [HttpPut("update-leave-request")] public IActionResult UpdateLeaveRequest([FromBody] LeaveRequestDto request) { // update an existing record return Ok(result); } [HttpDelete("delete-leave-request/{id}")] public IActionResult DeleteLeaveRequest(int id) { // remove a record return Ok(result); } } This is correct, and it's what most tutorials teach. But real enterprise systems — particularly HRMS and Payroll applications — frequently deviate from this pattern for reasons that only make sense once you understand what's actually happening to the data underneath. Why "Delete" Often Isn't Really DELETE Consider a leave request that an employee wants to withdraw. The textbook answer says: call [HttpDelete], remove the row from the database, done. In practice, most HR and Payroll systems don't want a "delete" action to genuinely erase the record. There are real, practical reasons for this: Audit trails – organizations often need to prove what happened and when, especially for anything touching attendance, payroll, or approvals. Permanently deleting a leave request destroys that history.Compliance – payroll systems in particular are subject to regulations that may require retaining records for a defined period, regardless of whether the user considers them "deleted."Traceability during disputes – if an employee claims a leave request was withdrawn incorrectly, having the original record (even if marked inactive) is the only way to investigate what actually happened. Because of this, many systems implement what's called a soft delete: instead of removing the row, the operation updates a status field: C# public class LeaveRequest { public int LeaveRequestId; public string EmpID; public int Status; // 0 = Pending, 1 = Approved, 2 = Withdrawn } A "delete" action becomes, in reality, an update to Status: C# [HttpPost("save-delete-role-mapping")] public IActionResult SoftDeleteLeaveRequest([FromBody] List<LeaveRequestDto> requests) { foreach (var req in requests) { req.Status = 2; // mark as withdrawn, don't remove the row } // save changes return Ok(result); } Because this is technically an update operation, not a true deletion, using [HttpPost] (or [HttpPut]) instead of [HttpDelete] is a defensible, common real-world choice — not a mistake or a shortcut. The verb should reflect what actually happens to the data, not just what the button on the screen says. Why POST Sometimes Wins Even for Genuine Deletes There's a second, more practical reason POST shows up in place of DELETE in real systems: payload complexity. [HttpDelete] is traditionally designed around simple identifiers, often passed in the URL: C# [HttpDelete("delete-leave-request/{id}")] public IActionResult Delete(int id) { // remove a single record by id return Ok(); } This works cleanly for deleting one record by one ID. But real operations are frequently batch operations — deleting or withdrawing multiple leave requests at once, each potentially needing additional context (who's performing the action, why, which workflow step it affects): C# [HttpPost("save-delete-role-mapping")] public IActionResult BatchDelete([FromBody] List<LeaveRequestDto> requests) { // process a batch of records, each carrying extra context return Ok(); } Passing a list of complex objects in a DELETE request body is technically possible but goes against how DELETE has traditionally been used and supported across tooling. POST, which has always supported rich request bodies, handles this case more naturally — which is exactly why it's common to see "delete" operations implemented as POST endpoints in real enterprise codebases. How This Looks From the Angular Side The verb choice on the backend directly shapes how the frontend calls it. In an Angular service, each HTTP verb maps to a specific HttpClient method: C# // GET - fetching data, no body needed getEmployeeDetails(empId: string): Observable<EmployeeDto> { return this.http.get<EmployeeDto>(`${this.apiUrl}/get-emp-details`, { params: new HttpParams().set('empId', empId) }); } // POST - creating a new record, or a batch/complex operation saveLeaveRequest(request: LeaveRequestDto): Observable<BaseResultModel<boolean>> { return this.http.post<any>(`${this.apiUrl}/save-leave-request`, request); } // POST used for a soft delete - batch of complex objects saveDeleteWorkFlows(models: LeaveRequestDto[]): Observable<BaseResultModel<boolean>> { return this.http.post<any>(`${this.apiUrl}/save-delete-role-mapping`, models); } Notice that both the create and the soft-delete operations use .post() from the Angular side, mirroring the [HttpPost] decorator on the backend. This consistency matters: if the backend soft-deletes via POST but the Angular service tries to call .delete(), the request will fail or hit the wrong endpoint entirely, since Angular's HttpClient.delete() doesn't send a request body the same way .post() does by default. Keeping verb usage consistent across frontend and backend isn't just a style preference — mismatched verbs are a common, easy-to-miss source of failed API calls that can take a while to diagnose, since the error often looks like a routing problem rather than a verb mismatch. A Note on Idempotency A related concept worth understanding alongside verb selection is idempotency — whether calling the same operation multiple times produces the same result as calling it once. GET, PUT, and DELETE are conventionally idempotent: fetching the same data twice returns the same result; updating a record to the same values twice leaves it in the same final state; deleting an already-deleted record (in systems that handle this gracefully) doesn't cause additional harm. POST is conventionally not idempotent — calling it twice can create two records instead of one. This matters directly for the soft-delete pattern discussed above. If SoftDeleteLeaveRequest is implemented as a POST that simply sets Status = 2, calling it twice by accident (say, from a double-clicked button or a retried failed request) produces the same end state — the record is still just marked as withdrawn. This is a case where a POST endpoint behaves idempotently in practice, even though POST isn't required to be idempotent by convention. It's worth being deliberate about this: an endpoint that changes a status flag is safer to retry than one that increments a counter or appends to a list, and understanding which category an operation falls into helps predict how it will behave under real-world conditions like network retries or double submissions. A Practical Rule of Thumb None of this means HTTP verb conventions don't matter — they're still a useful default. The practical guidance is: Use GET for anything that only reads data and has no side effectsUse POST for creating new records, and also for operations — including some deletes — that involve complex payloads or don't map cleanly to a single identifierUse PUT for straightforward updates to an existing, fully-identified recordUse DELETE for simple, single-identifier removals where a true, permanent delete is actually intended When you encounter an API that doesn't follow the textbook mapping exactly — like a "delete" endpoint implemented as POST — it's worth asking why, rather than assuming it's wrong. Often, as in the soft-delete case above, there's a real business reason: the data isn't actually being removed; it's being marked, and the verb reflects that reality rather than the UI label. Takeaway HTTP verb selection in a real Web API isn't just about matching a CRUD acronym to a decorator. It's about accurately representing what actually happens to the underlying data. A "delete" that's really a status update should probably be a POST or PUT, not a DELETE — and recognizing that distinction is a sign of understanding the system, not a shortcut around convention.

By Dhana PAMULA
Building Multi-Rail Payment Failover to Stop Latency Spikes and Double Debits
Building Multi-Rail Payment Failover to Stop Latency Spikes and Double Debits

Why Single-Gateway Payment Pipelines Break Under Concurrency When building enterprise retail and commerce platforms, many engineering teams treat payment processing as a standard REST API call. A point-of-sale (POS) terminal initiates a checkout request, the application layer sends the payload to a payment service provider (PSP), and the resulting network response (200 OK, 402 Declined, or 504 Gateway Timeout) determines order completion. It feels pretty simple, but there are three particular systemic weaknesses that need to be considered during high transactional traffic: Slow processors eat up your server resources: Payment gateways rarely crash cleanly without warning. Instead, response times gradually stretch from a fast 300ms baseline up to 8 or 10 seconds before failing. When your checkout service sits there waiting on hanging connections, it ties up worker threads and drains your server connection pools. Before long, your servers run out of capacity to handle new requests, turning an outside payment delay into a site-wide checkout freeze.The timeout blind spot: If a network connection drops halfway through a request, your server has no idea whether the card was actually charged. Triggering an immediate client-side retry risks hitting the customer with a duplicate charge. Aborting the order immediately loses revenue, even if a backup processor is sitting completely idle.Zero routing flexibility: When you're tied to one pipe, you take every hit directly. You can't steer transactions toward local acquiring banks to trim interchange fees, and you can't route around regional bank outages when an acquirer starts sputtering. Designing a Dynamic Multi-Rail Routing Engine The core shift here is treating payment processors as swappable endpoints rather than permanent integrations. We score and select gateways on the fly based on how they're performing in real time. Real-Time Routing Logic Before sending an authorization payload downstream, the engine runs through three rules: BIN and geography: The routing service reads the first 6 to 8 digits of the card number (BIN) against a local card table. Domestic cards route to local acquiring partners to keep interchange fees down and reduce false declines triggered by issuing-bank fraud filters.Rolling latency thresholds: We don't wait for a hard 500 error to react. The engine monitors p95 and p99 response times over rolling 60-second windows. If our primary processor averages over 1,500ms, non-essential traffic automatically shifts to a backup rail before shoppers ever see a spinning wheel at checkout.Circuit breakers: Every third-party integration is wrapped in a standard circuit breaker: Closed: Normal traffic routes to the primary processor.Open: If 5xx errors or timeouts cross 5% over 100 requests, the breaker trips to open. Inbound traffic bypasses that processor entirely, preserving server resources.Half-open: After a 30-second cool-down, small test probes check if the provider has recovered before routing production traffic back. Handling Distributed Idempotency and Preventing Double Charges The biggest hazard in multi-rail failover is the mid-flight race condition. If Gateway A slows down, your orchestrator might log a timeout after 3 seconds. If you switch to Gateway B without confirming the state of Gateway A, Gateway A might finish processing in the background. Now the customer gets billed on both rails, and your customer support queue explodes. How to Prevent It Deterministic Request Fingerprinting Every inbound transaction must carry an immutable idempotency key (UUIDv4) paired with a SHA-256 hash of the order details (amount, currency, merchant ID). If the same key arrives with different order values, reject it immediately with an HTTP 422 error. Atomic Redis Mutex Before calling any gateway API, grab a distributed lock using Redis (SETNX) with a short expiration (around 60 seconds). If a duplicate request arrives while the status is still in progress, return an HTTP 409 Conflict. The Void-Before-Switch Rule Never fail over blindly. If the primary processor times out, the system must issue a synchronous cancellation or void call to that processor first. Only when you receive a confirmed cancellation or a definitive decline should you release the lock and route the transaction to the fallback rail. If the void call also times out, drop the event into a Dead-Letter Queue (DLQ) for manual or asynchronous reconciliation rather than guessing. Edge-to-Cloud Integration and PCI-DSS Scope When deploying this model across retail store terminals and cloud backends, two practical operational considerations stand out: Keeping PCI-DSS Scope Manageable You never want raw Primary Account Numbers (PANs) flowing through multiple cloud services. Use a processor-agnostic vault at the edge to tokenize card details right at the terminal or browser level. The multi-rail routing engine should handle only universal tokens, exchanging them for processor-specific tokens via an isolated proxy right before dispatching the final API call. Offline Resilience for Physical Terminals Store terminals frequently face spotty internet connections. Keep local encrypted transaction logs on the hardware itself. If the store loses WAN connectivity, the terminal queues customer intents locally. When connectivity comes back, an asynchronous sync process drains the queue into the cloud routing layer without holding up customers in line. Production Realities and Tradeoffs Building a multi-rail payment layer adds upfront architectural complexity, especially around financial reconciliation and state management. Settling chargebacks across multiple acquirer dashboards requires tighter accounting controls than a single-gateway integration. However, for high-volume commerce platforms, the tradeoff is clear. When a downstream provider suffers an outage during a peak shopping day, an engine that fails over cleanly — without charging a customer twice — pays for itself immediately.

By Irfan Syed Ahmed
Your Event Storming Is Not Your Software Design
Your Event Storming Is Not Your Software Design

The Policy That Started the Argument We were looking at a purple policy between ListingSold and StopListingFee. Read aloud, the flow expressed a simple business expectation: when a listing is sold, the applicable recurring listing fee should stop. The interesting question was where that policy belonged. If Billing owns it, Billing receives the fact that a listing was sold and determines what that means for its fee model. Listing reports the sale without naming the operation Billing should perform. If Listing owns the coordination, it requests that Billing stop the fee, which means Listing knows that capability exists. A third option is a separate process manager that receives the sale event and coordinates the response. At the level of a simple event-policy-command sequence, these versions can look almost identical. Once ownership is made explicit, the differences matter. Billing depends on the sale event’s contract in the first version. The coordinating component depends on Billing’s command contract in the others. Billing still validates changes to its own fee model in every version. Responsibility for detecting an incomplete outcome, such as a fee that continues accruing after a sale, also needs an explicit owner. We were still discussing the business rule, but we were now deciding how software responsibilities and contracts would support it. This was already a discussion about where coupling belongs and how it is managed. We had moved into architectural reasoning without changing the business outcome we wanted. I later discussed this on LinkedIn and encountered the objection that EventStorming is not software design at all. I disagree, but the objection helped me distinguish two claims. EventStorming can host software design. It does not follow that the arrangement of a board is sufficient justification for the boundaries of the resulting system. This article is about that gap. EventStorming Already Includes Design The official EventStorming material explicitly recognizes Big Picture, Process Modeling, and Software Design formats. The patterns collection also addresses collaborative design activities. EventStorming is not limited to collecting domain events on a long wall of paper. The title therefore makes a narrower claim than it might suggest. “Your Event Storming” means the model your group produced, with its particular clusters, policies, and arrows. That model may contain exploratory ideas, agreed decisions, and reasons for those decisions. What cannot be assumed is that the notation alone captures all the reasoning needed to justify the resulting software structure. A policy between two notes expresses a relationship: when this happens, that response should follow. Unless ownership and the relevant assumptions are also made explicit, the sequence leaves important questions unanswered. Who owns the rule? Which contract does the response depend on? What happens if the response is rejected or never completes? A Software Design session can address those questions. It can expose invariants, clarify responsibilities, and help participants explore alternative models. The policy discussion above is an example of that work. The problem is automatic inference: treating a cluster as sufficient reason for a service, a purple note as a prescribed message handler, or a temporal sequence as an execution topology. This is related to the architectural decisions a domain model leaves open. Modeling can establish constraints and support architectural choices without uniquely determining how the system should be deployed or operated. Those choices can be discussed during the workshop. They still need reasons beyond the appearance of the board. Same Flow, Different Ownership For this example, Listing owns the listing lifecycle, and Billing owns the fee lifecycle. A sold listing should no longer accrue the applicable recurring fee. The precise rule, especially when stopping accrual becomes effective, still needs clarification. For now, consider three ways to allocate responsibility for the response. Alternative A: Billing owns the reaction. Listing records the sale and makes a ListingSold event available across an agreed boundary. Billing receives that fact, interprets it using its own rules, and invokes the appropriate fee behavior. Listing does not need to name StopListingFee. Billing now depends on the meaning and structure of the event it consumes. The event publisher needs an explicit compatibility policy, although that does not require exposing Listing’s internal domain event unchanged. Billing keeps the relationship between sale facts and fee behavior within its own model. That is useful when the rule belongs to Billing and evolves with its charging policies. The design still needs to account for delivery failures, processing failures, and missed reactions. Suppose Listing records a sale but the corresponding fee remains active. Who detects that discrepancy, and who resolves it? Billing may own both the reaction and reconciliation, but that responsibility must be explicit. Successful publication alone does not establish that the business outcome is complete. Alternative B: Listing owns coordination. Listing requests StopListingFee from Billing. Listing therefore knows a capability Billing exposes. Billing remains responsible for validating the request and protecting its own rules. The request could be synchronous or queued. Either way, the coordinating component needs to distinguish acceptance from completion and decide how to handle rejection, an unknown outcome, or a response that does not arrive within the expected time. This option is justified only if Listing’s responsibility genuinely includes coordinating the fee change. Emitting the original event is not enough to establish that ownership. Nor does the statement “the sale is complete only when the fee stops” settle the question by itself. That requirement establishes a business outcome; deciding which component should be accountable for achieving it is still design work. Listing-owned coordination becomes more plausible when Listing already owns the broader completion process and can manage it without absorbing Billing’s fee rules. If it starts calculating charges or reproducing Billing’s eligibility logic, the coordination boundary is leaking. Alternative C: A process manager owns coordination. A separate component tracks the cross-component outcome and requests work from the responsible participants. Listing still owns the listing lifecycle. Billing still owns fee behavior. The process manager owns the progress of the interaction. This helps when a sale triggers several participants, steps have deadlines, or unresolved cases need escalation. The manager can record that the sale was observed, that a fee-stop request was issued, and whether completion was confirmed. That visibility has a cost. The manager needs durable state, recovery behavior, and a policy for its own failures. Its commands may use the same capabilities Billing already exposes; participants do not necessarily need a new interface simply because a process manager is calling them. For a single reaction, introducing this machinery may be harder to justify than making Billing’s existing responsibility explicit. DesignMessage crossing the boundaryContract knowledgeAccountability for completionBilling reactsListingSold eventBilling understands the published sale contractBilling can own reaction and reconciliation; this must be agreedListing coordinatesStopListingFee command and an appropriate completion signalListing understands Billing’s exposed capabilityListing tracks the outcome if coordination belongs within its responsibilityProcess manager coordinatesSale event, fee-stop command, and completion or failure signalsThe manager understands the contracts required by the processThe manager tracks progress and escalation; its own recovery must also be designed These alternatives allocate responsibility differently. They do not divide neatly into a coupled design and a decoupled one. Contract knowledge is one form of dependency. Billing understands the sale event in Alternative A. Listing understands Billing’s command contract in Alternative B. The process manager understands the contracts needed to coordinate Alternative C. Runtime availability is a separate concern. A synchronous call may require the responder to be available immediately. Buffered communication can allow the sender to proceed while the receiver is unavailable, provided the system can retain and eventually process the pending work. That changes the timing of the dependency rather than removing it. Release coordination is another concern. Consumers and publishers need compatible contracts, but they do not necessarily need simultaneous deployments. The relevant question is how those contracts can evolve without silently changing the business meaning. Moving the policy changes some of these dependencies. It does not automatically reverse all of them. Nor does its position prescribe a transport: an event does not require Kafka, and a command does not require HTTP. What would favor one option? If Billing independently owns the rule connecting a sale to fee accrual, Alternative A is a strong candidate. If Listing already owns a broader completion process that legitimately includes requesting the fee change, Alternative B may fit. If the interaction needs its own lifecycle, deadlines, and recovery across several participants, Alternative C becomes easier to justify. The business flow is an input to that decision. Ownership, contract obligations, and failure handling determine whether the chosen design can support it. The Missing Question Is Often About Time The sequence ListingSold → StopListingFee leaves an important question unresolved: when should accrual stop? The policy note alone does not specify that. It could be the effective sale time, when the sale is recognized by the business. It could be when Listing records the change, or when Billing processes it. Those moments can differ. If the contract carries timestamps, their meanings need to be explicit. For example, a published event might distinguish the effective time from the time the sale was recorded: JSON { "type": "ListingSold", "eventId": "...", "listingId": "...", "effectiveAt": "...", "recordedAt": "..." } These fields make the distinction visible. They do not establish which timestamp Billing should trust or what it should do with it. If Billing calculates accrual using an authoritative effective time, delayed delivery need not change the amount ultimately owed. But the system may already have issued an invoice, collected payment, or shown an outdated balance. It still needs rules for adjustment and for what the customer sees before the correction completes. A timestamp helps preserve the meaning of the fact. It does not remove the consequences of learning about it late. Suppose the business accepts a delay before the balance reflects a sale, provided the final calculation uses the correct effective date. An asynchronous reaction may satisfy that requirement. Suppose instead that no fee-related charge may be issued after the sale is accepted. That requires a stronger coordination or validation mechanism than receiving a sale event later. Merely replacing an event with a queued command does not provide that guarantee either. Corrections expose further decisions. If the sale was recorded incorrectly, should accrual resume? From which date? If an older sale notification arrives after a correction, how does Billing recognize that it no longer represents the applicable state? These questions concern the business meaning of the update as much as its delivery. This is where business outcomes beyond aggregate boundaries become relevant. A process spanning Listing and Billing does not automatically require one aggregate or one distributed transaction. Billing can protect a local invariant, such as refusing to calculate accrual beyond its recorded stop date, while the broader process still fails to establish that date correctly. The cross-component outcome needs explicit completion and recovery semantics. Compensation is another business operation, with its own rules and potential failures, rather than a database rollback. Eventual consistency does not by itself establish that the relevant rule was interpreted correctly or that unresolved work will be detected and repaired. Durable publication, retries, and idempotent handling support the design. They cannot supply a business rule the participants have not agreed on. A Boundary Still Needs a Reason An event on the board is not automatically an integration event. ListingSold may initially describe a fact inside the Listing model. Exposing that fact to another component creates a contract that needs deliberate semantics and an evolution policy. The published representation may differ from the internal event. Likewise, a cluster of activities does not establish an aggregate merely because the notes appear together. The grouping must be examined against the rules that must remain consistent. An aggregate does not prescribe a microservice, and a bounded context does not prescribe an independent deployment. These distinctions are part of why Domain-Driven Design does not select an architectural style. The ownership alternatives also exist inside a monolith. Listing and Billing could be modules in one application, with Billing reacting to an in-process event or receiving an explicit request through a module interface. The questions about rule ownership and contract knowledge remain. The execution guarantees may be quite different, however. A synchronous handler participating in the same database transaction can fail together with the originating operation. A background handler in the same application may run after that transaction commits and require durable delivery and recovery. Sharing a deployment does not settle those choices, just as separating deployments does not settle ownership. An independent deployment therefore needs its own justification. Billing might have a materially different scaling profile, need isolation from listing traffic, or require a separate security boundary. Its team might need genuine release autonomy. A runtime constraint might be difficult to satisfy within the existing application. These are reasons to evaluate separation, rather than automatic instructions to introduce it. The costs are concrete. An interaction that was previously local may now time out or complete without the caller receiving confirmation. Contracts need to evolve while different versions coexist. Observability must follow a business outcome across processes. Data previously updated within one transaction may require a different consistency strategy. Independent deployment can reduce some coordination costs while introducing others. I would not impose a fixed sequence of aggregates first, contexts second, services last. Domain learning and architectural constraints inform each other. A scaling or compliance requirement can change where responsibilities execute or force us to reconsider a proposed partition. It does not automatically change the meaning of the business model. When a boundary changes, the team should be able to explain which concern required the change. What I Would Record Beside the Wall I would capture a short decision record while discussing each significant policy, rather than leave all the reasoning for someone to reconstruct after the workshop. First, who owns the rule connecting the fact to the response? In this example, does Billing own the rule relating a sale to fee accrual, or does a broader business process require that outcome? Billing owns the fee mutation in either case. The separate question is who initiates the response and tracks its completion. Next, which contract crosses the boundary? Who maintains it, and what changes can its consumers tolerate? A note on the wall becomes an integration commitment only when the participants agree on the meaning and obligations it carries. The record should also identify what must remain consistent, the acceptable delay between steps, and the effective time used when information arrives late. It should say who detects an incomplete outcome, who resolves it, and what counts as evidence of completion. Acceptance scenarios make those decisions harder to leave vague. The official Extract Acceptance Tests pattern connects design sessions with more precise expectations about behavior. For this example, I would include a sale received after an invoice was issued, a correction received before an older sale event, and a fee-stop request whose completion cannot immediately be confirmed. The expected result in each case needs to come from the business rule. The record should remain short enough to maintain. Its purpose is to preserve the reasons behind the model, including decisions deliberately left open. Six months later, another engineer should be able to distinguish an agreed constraint from a convenient assumption. Closing The discussion began with ListingSold, a purple policy, and StopListingFee. Asking who owned the policy led us to contracts, coordination, consistency, and recovery. That was software design taking place through EventStorming. The workshop can help a team make those decisions, and the board can record them. What the event sequence cannot provide on its own is the justification for a particular allocation of responsibilities or a particular deployment boundary. Billing might own the reaction. Listing might coordinate it. A process manager might track a broader outcome. Choosing among them requires knowing the rule, the timing requirements, and who is accountable when the expected response does not happen. The wall can show the flow. Your design must explain who owns each decision and what happens when the flow breaks. References and Further Reading Introducing EventStormingEventstorming PatternsExtract Acceptance TestsWhere Does Software Architect Fit in Domain-Driven Design?Modern Software Architecture (Part 2): Coupling Is Where Architecture Actually HappensDomain-Driven Design Beyond Aggregate BoundariesDomain-Driven Design Is Not an Architecture

By Alireza Rahmani Khalili DZone Core CORE
Delegated Transport, Forked Authorization: Where Chat and AI-Agent Integrations Actually Break
Delegated Transport, Forked Authorization: Where Chat and AI-Agent Integrations Actually Break

When you move messaging onto a third-party platform, you don't hand off the authorization problem. You split it across two systems. Most incidents live in the gap. A simulation harness, and a documentation audit of QuickBlox as a worked example. The Revoked User Who Kept Reading Say a clinic's app removes a contractor's access to a patient thread at 14:02. The app's database says so, the UI hides the thread, and the audit table has the row. The contractor's phone keeps receiving new messages until 15:00, and then keeps going. Nothing in the application is wrong. The membership removal went to the chat platform's API as a single best-effort call, and the API was having a bad ten minutes. The call failed, and the exception was swallowed. The contractor's session token is still valid, and the contractor's client keeps making requests that keep it valid. This is a hypothetical, but every piece is routine: a removal path with no retry, an admin API that can be unavailable, a session whose lifetime depends on activity. The useful question is how long the window lasts, and it becomes measurable once you stop treating the integration as an API call and start treating it as a consistency boundary. This article builds a small deterministic harness, seamlab.py, to measure that window along with seven other failures at the same boundary, including an AI agent acting after a human has taken over a conversation. It then audits one real platform, QuickBlox, against the same questions using its public documentation. QuickBlox is the worked example because its developer documentation is public and detailed enough to check. The harness measures a class of platforms and nothing about any vendor. The documentation audit reads documentation and tests nothing. I keep those two kinds of evidence apart throughout. The Flawed Assumption The usual framing of "build vs. buy" for chat or calling is about transport: delivery, ordering, presence, media. Delegating those is reasonable. But "who may read this thread, who may post, who may trigger an action" is not a transport concern, and delegating transport forks it: Your application holds the relationships: this clinician treats that patient, this contractor was removed.The platform holds a projection of them: dialog memberships, session tokens, message history. The projection is only as fresh as your last successful write to it, and the platform enforces the projection, not your database. So in at least two places answer "is this allowed," and they can disagree. Each failure below is a case of that disagreement, or of one side believing a claim the other never checked. Two quantities make this concrete. Revocation window W: the time between the app committing a revocation and the last successful read by the revoked principal. If the platform checks live membership on every read, W is bounded by the time until the removal call lands. If it authorizes from the session token alone, W is bounded by the token's remaining life, and whether that life is fixed or extended by activity decides everything.Authority provenance: for any action in the system, whose authority is it exercising? For a human action, the answer is trivial. For an AI agent in a multi-party conversation, it usually isn't. Threat Model Six attacker positions, all realistic for a chat integration: #AttackerCapabilityAExternalKnows the webhook URLBAuthenticated low-privilege participantCan post messages into a thread the agent readsCSelf-registered platform userPlatform allows signup, no verified binding to your user modelDRevoked participantHolds a valid token from before revocationEReplayerHas a captured, validly signed event (logs, proxy, compromised sink)FWriter on the audit storeCan modify rows Trust boundaries: client to app, app to platform (admin API), platform to app (event delivery), agent to tools, and the audit store. ClassPreconditionMechanismTestControlForged eventAUnauthenticated event endpoint acceptedforgedSignature verificationIdentity confusionCSender resolved by mutable attribute (email)spoofed identityImmutable-ID binding tableReplayEDedupe TTL shorter than replay horizonreplayTimestamp window plus retention ≥ 2×windowDuplicate side effectNormal at-least-once deliveryNon-atomic check-then-actraceAtomic claim before actingStale accessDToken and membership outlive revocationrevocation sweepShort TTL, outbox retry, token killAgent confused deputyBInjected text drives a privileged toolA1–A4Parameter-bound approvalPost-handoff actionRace with human takeoverAgent call in flight at handoffA5–A6Epoch fencingScope overreachBAgent reads history beyond sessionA7Capability-scoped history Audit tampering (F) is covered separately below. The Harness seamlab.py is about 480 lines of stdlib Python on a logical clock, with no network and no randomness. It contains: A platform simulator: at-least-once event envelopes signed with HMAC, expiring tokens with scopes frozen at mint, optional idle (sliding) expiry, self-service registration, and an admin API that can be switched off. Whether reads check live membership, and whether a server-side token kill exists, are switches.Two app implementations: a naive one and a hardened one.An agent world with a tool proxy configurable per control, so the table shows which control closes which attack.A worst-case agent: it obeys every CALL tool key=value line in its context. That is deliberate. The tests target the authorization layer and say nothing about how robust any model is to injection. If your model resists injection, that's a bonus. These controls assume it doesn't. The duplicate-delivery test enumerates every distinct interleaving of two workers handling the same event, rather than sampling a few. Naive Design, Then the Attacks The naive ingress handler is a shape I'd expect to find in plenty of codebases: no authentication on the endpoint, dedupe with a TTL, check then act then record, sender resolved by email. Python def handle(self, env): t = self.seen.get(env["id"]) # check yield if t is not None and self.clock.t - t < self.DEDUPE_TTL: # 300s return "dup" uid = self.resolve(env["body"]["sender"]) # email match if uid: self.run_command(uid, env["body"]["text"]) # act yield self.seen[env["id"]] = self.clock.t # record yield AttackNaiveHardenedForged unsigned eventsucceedsblockedValidly signed event, spoofed identitysucceedsblockedReplay at t+225 sblockedblockedReplay at t+3600 ssucceedsblockedDuplicate delivery: interleavings producing a double effect60 of 660 of 12 The spoofed-identity row is the interesting one. The event carries a correct platform signature. Nothing was forged. The attacker registered a platform account with email [email protected], unverified. The naive app lowercases and matches against its user table, so a perfectly authentic message from the wrong person runs with the clinician's authority. Signature verification can't help, because the signature is telling the truth about who sent it. The control is a binding table keyed on the platform's immutable user ID, written only by your backend when it provisions the platform user for an authenticated app user. The attacker's ID has no binding, so the event is rejected as unbound. The race result is worse than it looks. 60 of 66 distinct schedules double-fire. Only interleavings where the first worker finishes recording before the second starts checking are safe. This is the ordinary case for any retry storm. The fix is one atomic operation (SET NX EX, or an insert against a unique constraint) before any side effect. The hardened handler: Python def handle(self, env): if not hmac.compare_digest(env.get("sig", ""), sig_of(env)): return "bad_sig" if abs(self.clock.t - env["ts"]) > self.TOL: return "stale" ok = self.claim(env["id"]) # atomic set-if-absent, retention 2*TOL yield if not ok: return "dup" uid = self.bindings.get(env["body"]["sender"]) if uid is None: return "unbound" self.run_command(uid, env["body"]["text"]) yield return "ok" Mutation-Testing the Control The suite should be able to fail the hardened design; otherwise, the green column is decoration. So I mutated one parameter: dedupe retention set to half the timestamp tolerance. The replay at t+225 s then succeeds, because the event is still inside the accepted time window while its dedupe record has expired. The replay at t+3600 s is still blocked by the timestamp check. That yields an invariant worth writing into code review: dedupe retention must be at least twice the accepted timestamp skew (once for events slightly in the future, once for slightly in the past). Timestamp validation and dedupe are two halves of one control, and shortening either silently opens the gap. One caveat: claim-before-act gives at-most-once side effects if the process dies between claim and effect. For effects that must not be lost, the downstream operation needs its own idempotency key derived from the event ID. The harness does not model crash recovery. Revocation Window, Measured The harness drives a revoked user who keeps polling and refreshing, with the token's age at revocation sampled across its lifetime. The scenario that matters: the admin API is down when the revocation is issued and comes back 600 s later. In the first table, the platform checks live membership on every read: ConfigWorst W (s)Mean W (s)Token mints per user per hourNaive, TTL 3600, single attempt360018301Hardened, TTL 303016120Hardened, TTL 60603060Hardened, TTL 30030015212Hardened, TTL 9006014054Hardened, TTL 36006015561 "Hardened" means a transactional outbox retrying the removal with capped backoff, a broker that re-checks the app's authorization on every token mint, and a short TTL. Once TTL exceeds the outage, W is capped by the outage plus up to one backoff interval (601 s in this run). Below the outage length, TTL is the binding constraint. With a healthy admin API, every configuration, naive included, shows W = 0. The naive design only fails when the platform is degraded, which is when nobody is watching. When the Platform Doesn’t Check Membership, and Tokens Slide Two platform properties change the picture, and I only added the second after reading the vendor documentation described below, which is why the harness changed between drafts. If reads are authorized from the token alone, removal calls don't matter, and the TTL is the only built-in lever. If the token's expiry is idle-based, so each request pushes it out, then a revoked client that keeps making requests never lets the token expire, and the TTL stops being a bound at all. The broker's re-check at refresh never runs, because refresh never happens. The last control available is a server-side token kill, if the platform offers one. Results for a token-only platform (hardened TTL 60, naive TTL 3600; "never ends" means access persisted to the end of the simulated horizon): Expiry model, admin APINaiveHardened, no token killHardened + token killFixed TTL, healthy3600 s60 s0 sFixed TTL, 600 s outage3600 s60 s60 sIdle expiry, healthynever endsnever ends0 sIdle expiry, 600 s outagenever endsnever ends601 s Read the third row twice. With idle expiry and no kill, the short TTL and the broker re-check buy nothing against a client that keeps talking. The only controls that end access are live-membership enforcement on the platform or an invalidation you can trigger from the server. So the most valuable hour you can spend before integrating a platform is finding out which of those you have. At TTL 60, each active user generates 60 token mints per hour. Whether that is trivial depends on your user count and the platform's rate limits, which the harness does not model. The AI Participant: Confused Deputy, Not “Authorization for Bots” A multi-party conversation is a prompt authored by several principals with different privileges. The agent reading it holds one set of tool credentials. Any principal who can put text in the thread can attempt to spend authority they don't have. This is the classic confused deputy, with the deputy now parsing natural language. The harness has a dialog with a patient and a clinician, and three tools: get_my_record (low privilege), approve_refill (clinician only), and read_history. The proxy runs in three configurations: naive (the agent's standing credential decides everything), role-check (the call executes with the authority of whoever authored the triggering message), and hardened (role check plus parameter-bound approval, epoch fencing, and history clamping). AttackNaiveRole-check onlyHardenedA1 Patient's message steers agent into approve_refillsucceedsblockedblockedA2 Clinician's benign turn; patient's injected text sits in contextsucceedssucceedsblockedA3 Approval for rx42 reused to approve rx99succeedssucceedsblockedA4 One approval consumed twicesucceedssucceedsblockedA5 In-flight agent call executes after human takeoversucceedssucceedsblockedA6 New agent turn minted after takeoversucceedssucceedsblockedA7 Agent reads history outside session scopesucceedssucceedsblockedB1 Clinician approves refill through explicit approvalworksworksworksB2 Patient reads own record through agentworksworksworks The B rows make sure the hardened column isn't green merely because it denies everything. A2 is the finding that changed my plan. My pre-run design was authority as the intersection of the acting principals' rights. Role-check is that rule, and it stops the obvious attack (A1). It fails A2 completely. The clinician sends "please summarize the thread." The agent's capability is legitimately the clinician's. The patient's earlier message, still in context, asks for a refill approval, and the agent obliges, spending authority that was never granted for that purpose. Intersection scopes who the agent acts for. It says nothing about what that authority was meant to cover. The fix is to stop treating conversation turns as grants for privileged operations. A privileged call needs an approval bound to the exact call, issued out-of-band by an authenticated UI session of a privileged human: Python def _approval_ok(self, tool, args, ap): b = ap["body"] good = hmac.new( APP_KEY, json.dumps(b, sort_keys=True).encode(), hashlib.sha256, ).hexdigest() if not hmac.compare_digest(good, ap["mac"]): return False if (b["tool"], b["args"], b["epoch"]) != (tool, args, self.epoch): return False if self.clock.t > b["exp"] or b["nonce"] in self.used: return False if self.users.get(b["principal"]) != "clinician": return False self.used.add(b["nonce"]) return True The approval binds tool, arguments, epoch, expiry, and a single-use nonce. A3 fails because the arguments differ, and A4 because the nonce is spent. Injected text can still request the call. It cannot carry the authority to make it. The system doesn't try to detect injection. It makes sure injected text can't hold a capability. Fenced handoff (A5, A6). When a human takes over, the app increments a per-dialog epoch. Every capability carries the epoch it was minted under, and the tool proxy rejects stale ones. A5 is the race: a turn starts at t=0, the human takes over at t=5, and the agent's call arrives at t=8. Without the fence it executes. This is a fencing token, and it has a fencing token's limit: it only works if the resource performing the effect checks the epoch. If the agent can also post through a path that bypasses your proxy, such as the platform's own API with the agent's own credentials, the fence is decorative. The platform-side complement is removing the agent from the dialog at handoff, which is another admin call, subject to the same outage window measured above, and which not every dialog type allows (see below). History scope (A7). The capability carries the index where the current session begins, and read_history refuses anything earlier. The harness checks the proxy's enforcement. It does not check that the agent's context assembly respects the boundary, which is separate code you would need to test. The audit log, and what a hash chain does not do The hardened path records each agent tool call (allowed or denied) and each handoff in a hash-chained log with actor type, model version, tool, arguments, result, and principal: Clean chain, verified against an externally stored head hash: passes.Row modified without recomputing the chain: detected.Row modified and the chain recomputed from that row forward (an attacker with write access): verifies clean unless you compare against the externally stored head, in which case it is detected. The chain alone defends against accidental corruption and clumsy tampering. It does not defend against someone who can write the store and knows the scheme. What does is anchoring the head hash somewhere that an attacker can't write: a separate account, an append-only object store, a periodic signed checkpoint. If your threat model includes a malicious insider with database access, the anchor is the control, and the chain is the mechanism that makes anchoring cheap. On compliance: in a regulated setting, "who did what, when, under whose authority" is what this log makes answerable. The HIPAA Security Rule's audit-control standard is 45 CFR §164.312(b) (cited from memory; confirm before relying on it). A platform's compliance posture does not discharge your obligations, and a log design is one input to them, not compliance itself. A Documentation Audit: The Seam on Quickblox Everything above is simulation. This section asks the checklist questions of a real platform using its public developer documentation, retrieved on 4 October 2026. Nothing here was tested against a live QuickBlox account. Documentation can be incomplete or out of date, and where I could not find an answer, I say so instead of guessing. Sources are listed at the end. QuestionWhat the documentation saysConsequence for the seam1. Are server-to-app events authenticated?I found no first-party documentation of outbound server-to-server event webhooks. A competitor's comparison page asserts QuickBlox doesn't support webhooks. That is a competitor's claim and I haven't confirmed it.If there is no signed event feed, the forged/replay/race tests apply to whatever you build instead. The rule that survives is to never let your backend act on events reported by clients, because client-reported events are attacker-controlled. If you poll, poll with a server credential and treat the response as the source.2. Does a read check live membership, or only the token?Not stated in the pages I read.Unknown. This decides which row of the revocation tables applies. It is a two-minute sandbox test: remove an occupant, then read with that user's still-valid token.3. Token lifetimeBoth user and application session tokens expire 2 hours after the last REST request, and each REST response carries an expiry header. I found no configuration for it.This is idle expiry, which is the dangerous row of the table above. A client that keeps making REST calls keeps the session alive. I don't know whether live chat-connection activity also extends it, and I haven't verified an absolute cap.4. How is membership removed?Removal goes through the dialog update call. A dialog's owner can remove any occupant (the REST reference says admins can too), and an occupant can remove only themselves. The SDK and dashboard docs show removing other users working for group dialogs, not for private (one-to-one) or public ones. Deleting a user removes them from group dialogs but not from private dialogs' occupant lists.Private dialogs have no documented remove-another-user operation. If revocation matters, a clinician-patient conversation modeled as a private dialog can't be revoked by removal. You'd have to delete the dialog for everyone (which needs the owner and loses history). Model sensitive conversations as group dialogs with an app-controlled owner. This is a design decision to make before launch, not after.5. Immutable IDs, self-registrationUser creation with an application session is documented as acceptable for prototypes. For production the docs recommend creating users from your backend with the API key and disabling application-session user creation. Users carry an external_user_id field intended to link to an outside system, and login, email and external ID must be unique.The identity-confusion attack depends on that production setting. Bind your app user to the platform's own user ID, written only by your backend, and don't resolve senders by login or email. external_user_id is a convenient mapping field, but the binding should still be enforced on your side.6. Can the agent be a distinct principal?Dialogs have owner, admin, and occupant roles.Make the agent a separate user and an occupant, never an admin or owner. To fence it at handoff by removing it, the dialog must be a group dialog, per row 4. I did not verify whether the agent's session can be invalidated server-side.7. Can you reconcile after a missed event?Dialog and message REST endpoints exist, and the update and delete references show them taking an API key. I did not verify listing and filter semantics for drift detection.Plan the reconciler as a poll of dialogs and occupants compared with your database. Confirm pagination and filter support in a sandbox first. Three observations from the table, none of them about vendor quality. Every platform has choices like these, and every one is a place the seam can fail: The documented 2-hour idle expiry changes the revocation answer. In the harness's token-only, idle-expiry rows, short TTLs and broker re-checks buy nothing, and the only thing that ends access is membership enforcement or a server-side kill. Whether QuickBlox enforces membership at read time is the first thing to test, and whether you can invalidate a session from the server is the second.The private-dialog limitation is the most actionable finding. It is a design constraint you can only avoid by choosing group dialogs up front.The absence of a documented signed event feed moves work to you. The ingress hardening in this article becomes a design for whatever sync mechanism replaces it. On the vendor's compliance statements: QuickBlox's own pages state that it offers HIPAA-ready hosting with a signed BAA, and that it is SOC 2 certified. I haven't verified those claims, and a BAA does not make your application compliant. The seam problems in this article are exactly the part a BAA doesn't cover. Cost and trade-offs Ingress overhead. Hardened ingress costs about 8.8 µs per event against 2.0 µs for the naive handler, in-process, on one machine (Python 3.12). Indicative only. In production, the dominant cost is one atomic store write per event.Token churn. Short TTLs convert revocation latency into mint load: 60 mints per user-hour at TTL 60, 120 at TTL 30. And if expiry is idle-based, TTL tuning may not be available to you at all.Dependence on the admin API. Forced removal and token kill are only as available as that API. The outbox hides outages from the revoking caller. It doesn't shorten them.Approval friction. Every privileged action needs a human click bound to specific arguments. The agent can't autonomously perform privileged operations. That is the intended outcome, and it will frustrate some product teams. Mitigate it with a good approval surface: show the exact arguments, make approval one tap, and expire quickly.Complexity. The hardened design adds a broker, an outbox, an approval service, a per-dialog epoch, and an anchored log. For an internal tool with a few trusted users, it is probably more than you need. Limitations of this work The simulator is simple: one dialog, instantaneous admin success when up, no clock skew, no partial failures inside the platform, a single-node claim store.The worst-case agent models the threat, not any LLM.I did not implement or test a membership reconciler, although I recommend one.The QuickBlox audit is documentation-only. Docs may be incomplete, inconsistent (the owner-versus-admin removal rule is stated differently in different pages), or out of date. Every "unknown" in the table is a sandbox test I haven't run.Remaining exposure none of this addresses: injected text can still influence unprivileged tools (what the agent says, what it summarizes), exfiltration through in-scope reads, and approval fatigue.Nothing here shows that any real platform is vulnerable to any attack in the harness. Conclusion The integration boundary is a consistency boundary, and the interesting failures are state disagreements and authority crossing it unchecked. The revocation window gives you a number to argue about, instead of a feeling, and the number depends on three platform properties you can look up before writing code: whether reads check live membership, whether token expiry is fixed or idle-based, and whether you can remove a member or kill a session from the server. For the AI participant, the real question is whose authority a tool call exercises. Intersecting principals' rights is necessary but not sufficient. A privileged call needs an approval bound to its exact arguments, or conversation text will eventually carry authority it shouldn't. Sources (QuickBlox documentation, retrieved 4 October 2026): Key Concepts: https://docs.quickblox.com/docs/key-conceptsAuthentication (JS): https://docs.quickblox.com/sdks/js-authenticationUpdate Dialog: https://docs.quickblox.com/reference/update-dialogiOS Dialogs: https://docs.quickblox.com/sdks/ios-chat-dialogsDashboard, Chat: https://docs.quickblox.com/docs/chat-dashboardDashboard, Users: https://docs.quickblox.com/docs/users-dashboardCreate User: https://docs.quickblox.com/reference/create-userDelete Dialog: https://docs.quickblox.com/reference/delete-dialog

By Igboanugo David Ugochukwu DZone Core CORE
A Non-Expiring AKS Deployment Token Could Read Secrets Across Three Namespaces
A Non-Expiring AKS Deployment Token Could Read Secrets Across Three Namespaces

A security review started after connection strings were visible through a Kubernetes management tool. The first request sounded simple: remove Secrets from the cluster and move the values to Azure Key Vault. That request focused on which system stored the values. The access review found a wider problem. Kubernetes stored a deployment service account's legacy token in a kubernetes.io/service-account-token Secret. The token had no expiry in its normal use, and RoleBindings allowed the same identity to operate in three application namespaces. The Role used resources: ["*"] across several API groups and allowed get, list, watch, create, update, patch and delete. The Role included the core API group, so the token could read every Secret in each of those namespaces. The review found no evidence of token misuse. It found an avoidable access path with a long lifetime and a larger scope than the pipeline needed. Moving application passwords to Key Vault would improve their source of truth and rotation. It would not revoke this token, narrow its RBAC permissions or remove the cross-namespace bindings. Those controls needed their own fix. Why the Kubernetes Secrets Existed The application images carried JSON configuration files for local development. Database, cache and message-broker endpoints pointed to localhost. Those defaults were useful on a developer machine and unusable inside the cluster. The shared Helm chart supplied the deployment values at runtime. It rendered an Opaque Secret from a secrets map, then loaded the Secret into the application container through envFrom. The reduced chart looked like this: YAML {{- if .Values.secrets } apiVersion: v1 kind: Secret metadata: name: {{ include "app.fullname" . }-secrets type: Opaque stringData: {{- range $key, $value := .Values.secrets } {{ $key }: {{ $value | quote } {{- end } {{- end } The Deployment then loaded every entry as an environment variable: YAML envFrom: - secretRef: name: {{ include "app.fullname" . }-secrets The application configuration placed environment variables after the file-based settings, so the runtime values won. That ordering made the Kubernetes Secret part of the configuration path. Removing it without replacing that path would leave the containers pointing at local services. Figure 1. The existing deployment used a Kubernetes Secret as the runtime override for local file defaults. The next question was, "Which components can retrieve the value, and how long does each form of access last?" Key Vault Does Not Always Remove the Kubernetes Secret The Azure Key Vault provider for the Secrets Store CSI Driver supports more than one consumption model. A pod can read mounted files directly from a CSI volume. This path can avoid creating a native Kubernetes Secret. The application still needs a configuration method that reads those files and responds safely when their contents rotate. The driver can also copy mounted values into a native Kubernetes Secret through the secretObjects field of a SecretProviderClass. Microsoft documents this as secret synchronisation. It is useful when an application already consumes secretKeyRef or envFrom, which was the case here. It also means that moving the source value to Key Vault does not remove the Secret object from Kubernetes. YAML apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: app-vault spec: provider: azure secretObjects: - secretName: app-runtime-secrets type: Opaque data: - objectName: database-password key: Database__Password The choice affects rotation too. Microsoft notes that an existing process does not receive updates when a container consumes a Kubernetes Secret through an environment variable. The team must restart the pod before the process receives the new value. Key Vault remains a sound source for secrets. The important point is narrower: the storage migration and the Kubernetes access review solve different problems. The Service Account Crossed Namespace Boundaries The next part of the review followed the identities that could read Secrets. Kubernetes allows a RoleBinding in one namespace to name a ServiceAccount from another namespace. That feature is useful for controlled cross-namespace work. It also means that checking only the ServiceAccount's home namespace can understate its reach. The review found a layout equivalent to this generalized example: YAML apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: pipeline-deployer namespace: environment-b rules: - apiGroups: ["", "apps", "batch", "autoscaling", "networking.k8s.io", "policy"] resources: ["*"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: pipeline-deployer-from-a namespace: environment-b subjects: - kind: ServiceAccount name: pipeline-deployer namespace: environment-a roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: pipeline-deployer Two bindings of this form extended the identity from its home namespace into two more namespaces. The same bearer token could therefore authenticate once and use the permissions that each Role granted. Figure 2. Two cross-namespace bindings extended one long-lived credential into three namespaces. The identity was not a cluster administrator. The Role listed its API groups, and it did not include rbac.authorization.k8s.io. The token could not grant itself new RoleBindings through this Role. That limit mattered, but it did not make the existing scope acceptable. The core API group still covered Secrets, and the wildcard resource rule covered much more than the deployment needed. The following authorization check avoids printing any secret value: Shell identity="system:serviceaccount:environment-a:pipeline-deployer" for namespace in environment-a environment-b environment-c do printf '%s: ' "$namespace" kubectl auth can-i list secrets \ --namespace "$namespace" \ --as "$identity" done For the reviewed identity, the effective result was yes in all three namespaces. The Token Type Made the Scope Harder to Contain The service account had one manually created Secret of type kubernetes.io/service-account-token. Kubernetes describes this as a legacy mechanism that provides a long-lived credential. The current documentation recommends the TokenRequest API for short-lived tokens instead. The difference changes the failure window. A deployment job can request a token that expires shortly after the job finishes. If someone copies a static token into a CI/CD service connection, that credential can remain useful until somebody deletes or rotates it. An old export, agent workspace or copied configuration can preserve the same access during that period. The cluster version already supported projected service account tokens. Another environment-specific service account had no legacy token Secret, which confirmed that the static pattern was not present in every namespace. The First Fix Reduces the Token's Reach The quickest containment step is to remove the two cross-namespace RoleBindings. That immediately reduces the token's potential reach from three namespaces to one without changing the applications. Each environment should then have its own deployment identity, Role and RoleBinding. A pipeline for one namespace should not borrow the service account from another. This keeps the credential, audit trail and revocation boundary aligned with the environment it deploys. The desired shape is simple: Plain Text pipeline A uses a short-lived token for its Role in namespace A pipeline B uses a short-lived token for its Role in namespace B pipeline C uses a short-lived token for its Role in namespace C These deployments require no cross-namespace subject. Figure 3. The target design aligns one service account and its short-lived token with one namespace. A Short-Lived Token Replaces the Static Credential Kubernetes can issue a bounded token with the TokenRequest API. kubectl create token is a convenient way to exercise that API: Shell kubectl create token pipeline-deployer \ --namespace environment-a \ --duration 15m The command covers only one part of a CI/CD design. The runner still needs a trusted way to request the token. The pipeline should receive the credential at run time, the requester should limit its audience, and the token should expire soon after the deployment window. The service connection must stop storing the old bearer token before that change has value. After the new path succeeds, delete the legacy token Secret and confirm that the API rejects the old credential. Explicit RBAC Replaces Wildcard Access resources: ["*"] made future chart changes part of the role automatically. Kubernetes warns that wildcard rules can grant access to resource types that future API extensions add. A deployment role should name the resource types and verbs the release actually uses. The rendered manifests provide the initial resource list: Shell helm template app ./chart \ --namespace environment-a \ --values values.environment-a.yaml \ > rendered.yaml Inventory every apiVersion and kind in that output. Then compare the result with deployment calls in API audit logs or a dry run. The resulting Role may need access to Deployments, Services, ConfigMaps, Secrets, Jobs, Ingresses and autoscaling resources. It should not receive every resource merely because the chart might use one later. If a separate controller owns runtime Secrets, the deployment identity can lose Secret write access as well. If Helm still renders those Secrets, the role needs the exact verbs required by that release process. The policy must match the delivery design instead of hiding a required permission until the next deployment fails. The Review Found Other Paths to the Same Values The cluster token was the widest durable access path that the review found. Several pipeline variables also stored credentials as ordinary variables. Azure DevOps treats secret variables as protected resources. It encrypts their values at rest and masks exact values in logs. A task can still send a value elsewhere, and masking does not always hide partial strings. Marking the variables as secret still removes routine plaintext visibility from the library interface and logs. The remediation plan combined four related controls: Mark credential variables as secret and restrict which pipelines can use each variable group.Remove routine human permission to read Kubernetes Secrets through cluster tools.Rotate the database, cache and broker credentials that broader access paths exposed.Move non-sensitive settings out of the Helm secrets map and into a ConfigMap. Moving non-sensitive settings to a ConfigMap makes the review surface honest. Feature flags, log levels and endpoint names do not need to sit beside credentials merely because the original release populated only one values map. Validation Uses the Identity's Point of View The validation must test permissions from the identity's point of view. For each deployment identity, build an explicit matrix: Plain Text own namespace other namespaces read required objects yes no apply release objects yes no read application Secrets only if required no modify RBAC no no Then verify the old paths: the deleted legacy token fails authenticationeach identity returns no for Secret access outside its namespacethe pipeline can still deploy and roll backvariable-group values appear masked in the interface and logscluster users without an operational need cannot reveal Secret valuesrotated application credentials work and the previous values fail This sequence keeps the deployment usable while shrinking the access path in measurable steps. Secret Location and Secret Access Need Separate Reviews The visible Kubernetes Secret started the investigation, but deleting that object first would have left the long-lived deployment credential untouched. Using CSI secret synchronization could even have recreated the same type of object from a better source. The useful review order was identity, scope, lifetime, source and rotation. It exposed one token that crossed three namespace boundaries, wildcard permissions that exceeded the release surface, and pipeline values that lacked basic secrecy controls. Key Vault can improve storage and rotation. Short-lived credentials and narrow RBAC control who can reach the Kubernetes API. Environment-specific identities contain the effect of a leaked token. These controls work together, and none of them can substitute for the others. References Kubernetes documentation: SecretsKubernetes documentation: Service AccountsKubernetes documentation: Managing Service AccountsKubernetes documentation: RBAC good practicesMicrosoft Learn: Azure Key Vault provider configuration options for AKSMicrosoft Learn: Access Key Vault through the CSI Driver on AKSMicrosoft Learn: Secrets in Azure PipelinesMicrosoft Learn: Manage Azure Pipelines variable groups

By Ahmed Tariq
How To Build a Scalable SaaS Product Architecture
How To Build a Scalable SaaS Product Architecture

Most SaaS teams get the scaling question backward. They spend around six months debating Kubernetes clusters and microservices for a product that has limited customers. And when the same team gets an enterprise client — and suddenly has 500 concurrent users, the database falls. This is because no one thought about connection pooling. The architecture decisions that actually matter for SaaS product aren't about picking the trendiest stack. They're about sequencing. Which parts of the system need to scale on day one, and which parts can wait until there's real traffic to justify the complexity. A payments startup I've seen referenced in postmortems rebuilt its entire auth layer twice in eighteen months. First to add multi-tenancy, then again to fix a data leak between tenant accounts that never should have been possible in the first place. This piece walks through the architectural decisions that hold up as a SaaS product goes from ten users to ten thousand: how to structure the application layer, what multi-tenancy actually requires, and where security has to be built in rather than patched on later. What SaaS Architecture Actually Means SaaS architecture is the technical blueprint for how a product gets built, deployed, and shared across every customer using it. A desktop app or an internal company tool typically serves one user or one organization. SaaS application architecture is different because it needs to run different customer accounts on the same codebase and the same database. It has a shared setup, and that is the reason SaaS works as a business model. One codebase, sold repeatedly, instead of a fresh install for every buyer. But it changes what a bad query or a bad index actually costs you. On a single-tenant system, a slow query is one customer's problem. On a multi-tenant platform, that same query can drag down everyone who happens to be logged in when it runs. Solid SaaS architecture plans for this early. Teams need to figure out how many concurrent users the system can handle, how tenant data stays separated on shared infrastructure, and how new capacity gets added as signups grow. Updates need a path to production that doesn't take the whole platform offline. None of this requires unusual technology. It requires making these calls while the codebase is still small enough to change your mind cheaply. Start With a Modular Monolith, Not Microservices The architecture decision that shapes everything downstream is whether to start with microservices or keep things simple. Most teams get this wrong in the same direction. The Cost of Splitting Too Early A lot of SaaS product development advice treats microservices as step one, and that's backward for most teams. Once you split a product into a dozen independently deployed services, someone has to manage network calls between them, handle service discovery, and debug failures that span multiple systems. A five-person engineering team rarely has the bandwidth for that on top of building the actual product. What a Modular Monolith Looks Like Most SaaS teams don't need thirty microservices. They need one codebase that's organized well. A modular monolith ships as a single app, but internally, billing code lives in a billing module, user accounts live in their own module, and the core product logic stays separate from both. Each piece owns its own data and only talks to the others through a defined interface. Splitting things out later isn't painful if you set it up this way. Say billing starts getting heavier traffic than the rest of the app. You already have a clean boundary around it, so turning it into its own service is a deployment problem, not a rewrite. Real Companies That Stayed Monolithic Basecamp built on Rails and stayed on a monolith for over twenty years while serving millions of users. Shopify did the same thing on a modular Rails codebase, well past the point where a lot of engineering blogs said they should have moved to microservices. They eventually split off specific pieces, but only once those pieces had scaling needs the rest of the platform didn't. When Splitting Actually Makes Sense Forget team size or how much funding you've raised. Look at whether different parts of your SaaS application architecture need separate scaling, separate release schedules, or separate infrastructure. If billing and your core product feature grow together and the same engineers maintain both, there's no reason to pull them apart. Microservices fix a coordination problem. That problem shows up once a system gets big. Building for it before you're big just adds latency and more moving parts to maintain. What Is Multi-Tenant Architecture in SaaS Basic Definition Multi-tenant architecture in SaaS means multiple customers, or tenants, share the same application and often the same database, but each tenant's data stays walled off from the others. One codebase, one running instance, thousands of accounts on it. Nobody sees anyone else's data. That's different from giving each customer their own separate deployment, which is still how a fair amount of older enterprise software works. Multi-tenancy is what makes it possible to support a few thousand customers without babysitting a few thousand installations. The Three Isolation Models There are three common ways teams set up tenant isolation, and I've watched companies pick the wrong one for their stage more than once. Siloed isolation gives each tenant a fully separate database. It's the safest option and the easiest one to explain to a security auditor. It's also expensive past a certain point. I know a healthcare SaaS company that ran siloed databases for its first 40 enterprise clients and then spent three months just automating the database provisioning process, because doing it by hand had become a full-time job for someone. Pooled isolation is the opposite extreme. Every tenant lives in the same tables, tagged with a tenant ID column. Cheap, scales fine, and it puts nearly all the isolation burden on your application code getting every single query right. Forget a WHERE clause once, and you've leaked another company's data. This is where most of the ugly security incidents in SaaS come from, not from hackers, but from a developer who missed a filter on a Tuesday afternoon. Bridge isolation, also called schema-per-tenant, splits the difference. Same database, separate schemas per tenant. Costs less than siloing, still gives you a real boundary instead of relying purely on application logic. Most products that get past a few hundred customers land on pooled or bridge, then add row-level security at the database level as a backstop, so a missed query filter doesn't turn into a headline. Multi-Tenant SaaS Architecture Best Practices Picking an isolation model is step one. Making it actually hold up under real traffic is a different problem, and it's the one that bites teams later. 1. Enforce Isolation at the Database Layer Row-level security should sit at the database layer, not just in your application code. Postgres has native RLS policies for exactly this reason. Enforce tenant filtering at the query engine, and even a buggy application query can't accidentally cross tenant lines. Relying on application code alone means every engineer who ever touches the codebase has to remember the tenant filter, on every query, indefinitely. Sooner or later somebody forgets. 2. Watch for Noisy Neighbors One tenant running a bulk export or a heavy report can drag down query times for everyone else sharing that database. I've seen a single client's 2-million-row export slow the whole platform to a crawl during business hours. Connection pooling limits per tenant help. So does routing heavy jobs like exports and report generation into a separate queue — away from regular user traffic. 3. Tag Every Cache Key With a Tenant ID Caching gets trickier with multiple tenants sharing infrastructure. A cache key without a tenant identifier baked into it is a bug waiting to happen. I've seen a caching layer serve Tenant A's dashboard data to Tenant B because the cache key was just dashboard_summary instead of dashboard_summary:tenant_492. Every cache key, every session token, every background job payload needs the tenant ID attached, no exceptions. 4. Automate Tenant Provisioning Before You Need To Tenant provisioning also needs to be automated early, even if the first version is a single script. Manually setting up a new tenant's schema or database entry works fine for your first ten customers. It falls apart around customer thirty — by then you're doing it under pressure because sales already promised a launch date. The Core Infrastructure Layers Once the application logic and tenant model are settled, the rest of the system comes down to a few layers that each need to do one job well, without leaning on each other to cover for gaps. 1. Application Layer Session data goes into Redis, not local server memory. This is what makes horizontal scaling actually work. When sessions live centrally, a load balancer can route a user's next request to any server in the pool, and it doesn't matter which one handled their login. Skip this step, and users get logged out at random whenever a server gets cycled out during autoscaling. Kubernetes and ECS solve the scaling mechanics. They don't fix a stateful app. 2. Data and Queue Layer PostgreSQL or Aurora with read replicas is the standard setup past a few thousand users. Writes go to the primary, reads spread across replicas, and dashboard queries stop competing with transactional writes for the same connections. Queues handle everything that doesn't need to finish before a response goes back to the user. Sending an email, generating a PDF, processing an uploaded file. Drop these into SQS or a Redis-backed job runner, return the response immediately, and let a background worker pick it up. Report generation is the classic case where teams skip this early and pay for it later, since a report that takes eight seconds to build will tie up a web server for eight seconds per request if it's running inline. 3. Automation and Observability Terraform for infrastructure, CI/CD for deployments, Grafana or Datadog for monitoring. Set these up from the start rather than after the first outage. Dashboards catch a database running near capacity days before it turns into customer complaints about slow page loads. Security Considerations for SaaS Architecture Security in a multi-tenant system isn't a feature you bolt on before a compliance audit. It's a property of the architecture itself, and it either works because of how the system is built or fails because of how it wasn't. 1. Tenant Data Isolation Under Load Every isolation model discussed earlier, siloed, pooled, or bridge, needs isolation enforced at more than one layer. Application-level checks catch most mistakes. Database-level row security catches the ones that slip through code review. Relying on a single layer means one bug becomes a breach instead of a near miss. 2. Authentication and Authorization at Scale Auth gets more complicated once you're dealing with tenant-level roles on top of user-level permissions. A user might be an admin for one tenant and a regular user on a different account if your product allows multi-org membership. Token scopes need to carry tenant context, not just user identity, or a valid session for one account can end up touching data in another. 3. Encryption Boundaries Data needs encryption at rest and in transit, but the boundary that actually matters for SaaS is key management per tenant, particularly for enterprise customers who ask about it directly during procurement. Some products use a shared encryption key across all tenants. Others generate a unique key per tenant so a compromised key doesn't expose the whole customer base at once. The second approach costs more engineering time up front and saves you from a much worse conversation later. 4. Compliance Triggers as You Grow SOC 2 and GDPR requirements don't show up on day one, but the architectural decisions that make compliance possible do. Audit logging, data retention controls, and the ability to fully delete a tenant's data on request are much easier to build in from the start than to retrofit once an enterprise prospect asks for a SOC 2 report during contract negotiation. I've watched a sales cycle stall for two months while an engineering team scrambled to add audit logs that should have existed already. Common Scaling Mistakes to Avoid Before Building a SaaS Architecture Most of the problems that show up later trace back to a handful of decisions made early, usually for reasonable-sounding reasons at the time. 1. Splitting Into Microservices Before There's a Reason To This one keeps coming up because it's the most common piece of bad advice in SaaS engineering circles. A team with six engineers and no paying customers yet decides to build fifteen microservices because that's what they read scales. Then they spend more time debugging service-to-service network calls than building the product features that would actually get them customers. 2. Storing Session State on the Application Server Local session storage feels harmless until you try to scale horizontally and discover half your users are getting logged out every time a server restarts. This is usually caught late, often during the first real traffic spike, because it works fine at low volume and only breaks once load balancing starts routing users unpredictably across servers. 3. Skipping Read Replicas Until the Database Is Already Struggling Adding a read replica takes an afternoon when your database is healthy. It takes a stressful weekend when your primary database is already choking under load, and every dashboard query is competing with checkout transactions. Teams tend to wait until performance is visibly bad before setting this up, which is exactly backward. 4. Treating Security as Something to Add Before the Compliance Deadline Row-level security, audit logging, and tenant-scoped encryption keys are all much cheaper to build into the initial schema than to retrofit onto a database with millions of existing rows. I've seen a data migration to add proper tenant isolation take longer than the original feature that needed it. When to Bring in Outside Architecture Expertise Not every team needs to hire this out or figure it out alone. The right software development team structure can provide the expertise needed to scale efficiently. 1. Signs You Need Outside Help A SaaS architecture consultant earns their fee when a team is making irreversible decisions without the experience to know which ones are irreversible. Choosing a multi-tenant isolation model is one of those. So is picking a database that can't handle your projected write volume two years out. If nobody on the team has taken a SaaS product through a scaling event before, an outside consultant who has seen the same mistakes across a dozen other companies can save months of rebuilding. The opposite signal matters too. If your team already has someone who's built multi-tenant systems before, bringing in a consultant to re-litigate decisions that person already knows how to make just slows things down and adds a layer of translation between the person with the answer and the person implementing it. 2. Build In-House vs. Bring in Specialized Support Full SaaS product development makes more sense when a company needs to move fast on a product with no existing engineering team, not when an established team needs a second opinion on one architectural decision. Hiring a fractional consultant for a two-week architecture review costs a fraction of what a bad multi-tenancy decision costs to unwind eighteen months later, after customer data is already sitting in the wrong shape across a production database. The decision comes down to a specific question, not a general one: is the problem "we don't know what to build" or "we don't have enough hands to build it"? Those need different kinds of outside help, and a lot of engagements go sideways because a team hired for one problem while actually having the other. Conclusion Building a SaaS product that holds up under real usage comes down to sequencing decisions correctly, not chasing the most sophisticated stack available. Start with a modular monolith. Get multi-tenant isolation right at the database layer, not just in application code. Keep application servers stateless so horizontal scaling actually works when you need it. None of this is exotic engineering. It's a set of ordinary decisions made at the right time, before the codebase gets big enough that reversing course means months of migration work instead of an afternoon of refactoring. If you're mapping out architecture for a new SaaS product, it's worth getting a second set of eyes on the isolation model and data layer decisions before they're locked into a production schema.

By Megha Verma
The Permission Was Valid. The Action Was Not Authorized.
The Permission Was Valid. The Action Was Not Authorized.

Every incident review has a moment where someone asks how the thing was even possible. For agentic AI, the uncomfortable answer is often that everything worked as designed. The credentials were real. The API accepted them. The identity system confirmed the agent was allowed to call that endpoint. And the organization still ended up with an action nobody wanted. That gap is what Salt Security's State of Agentic AI and API Security 2H 2026 puts numbers on. The report surveys more than 380 security and technology professionals and adds telemetry from Salt Labs, the company's research arm. I read it as a security argument, not a scare statistic, so here is what the data supports and where it needs care. The Headline: Read Carefully The number everyone will quote is 49.8%. That share of respondents confirmed or suspected that an AI agent in their organization took an action in the past 12 months that the organization did not intend, expect, or authorize. Read the fine print and the picture gets more interesting. Only 25.3% report confirmed instances. Another 24.5% suspect it happened but could not prove it. A further 12.3% said they would not currently be able to determine whether it happened at all, and 15.4% did not know. Only 22.5% said it had not happened. So one in four organizations has a confirmed case, and a large share of the organizations cannot rule one out. That second group may be the more important finding, because an organization that cannot answer the question has a different problem from one that answered yes. What These Incidents Actually Look Like Among respondents with a confirmed or suspected event, the report breaks down what the action involved. Respondents could pick several outcomes, so the figures overlap: 53.9% reported an external API call or transaction.49.7% reported a configuration or permission change.41.9% reported modified or deleted data.37.2% reported contact with a customer, partner, or third party.32.5% reported access to data the agent should not have had.Only 9.9% said there was no material impact. These are changes in state, made in real systems. When a chatbot gets something wrong, someone reads a wrong answer. When an agent gets something wrong, money moves, records change, or a customer receives a message. I think this is the line security teams should draw: the risk is no longer in what the model says, but in what the system around it is allowed to do. Why Valid Access Is Not the Same as Authorization Authentication tells you who is calling. Permission tells you what that caller may touch. Neither tells you whether this specific action, at this moment, serves what the humans actually asked for. Salt Security's report makes a related point about identity. Only 26.1% of respondents say their agents get dedicated identities with scoped permissions. Another 24.3% use dedicated identities with broad permissions. The rest is a patchwork: 8.1% use shared service accounts, 5.2% use human user credentials, and 7.6% rely on embedded credentials or API keys. About 17.5% say it varies by application. The report bluntly states that a dedicated identity is necessary but not sufficient. A clearly-labeled agent with too much privilege can still do serious damage. The coverage data sharpens the point. Respondents report dedicated controls for AI agents (56.4%) and APIs (55.9%), but only 26.6% for agent identities and 24.8% for agent tools. Those two are exactly where an agent gains the ability to act. The Chain Nobody Designed Part of why security is hard is architectural. The report finds that 76.8% of organizations have agents that invoke other agents or tools that themselves call APIs. For 20.4%, this happens routinely. By the time a request reaches the system that changes something, the original instruction can be several steps behind it. A security control that evaluates each API call in isolation sees a legitimate request from a legitimate caller. It cannot see that the intent behind the call drifted three hops ago. This is why the report defines the agentic path as the full sequence from instruction, through the model's reasoning, and the tools and servers it invokes, to the API call, and the outcome. I find this framing useful because it gives defenders a unit of analysis that matches how the system actually behaves. Can You Reconstruct What Happened? Here the numbers are hard to wave away: only 12.5% of the organizations can consistently trace an agent's complete path across all agents, and 38.6% can trace the path. Asked how long it would take to determine every action a specific agent took the previous day, only 15.7% said it would take them minutes, but with automated tooling. 36% said hours of manual log correlation, and 28.5% said days and multiple teams. That means 64.5% of these organizations are looking at hours or days to determine the agents' actions in a single day. Hours matter when the actor is software. An agent can repeat an action, call several services, and change configurations without waiting for anyone's workday to start. Accountability looks somewhat better than visibility: 20.9% can name the responsible human or team for all agents, and 51.2% for most. But as the report notes, knowing whose agent it was does not tell you what it did. Stopping It Is Mostly a Human Job Only 17.5% can automatically stop an agent that begins behaving unexpectedly in production. About 56.1% can stop one manually within minutes. 12% can only take the whole application down, 3.1% cannot stop it, and 11.2% do not know. So 85.6% have some way to intervene, but it all depends on a person noticing the anomaly. The report's recommendation for prevention is the part I would emphasize. A kill switch is useful, but it should not be the only thing standing between an odd decision and an irreversible action. The stronger design is preventive and layered: least privilege on the agent identity, explicit policy at the tool and API boundary, step-up human approval for sensitive operations, transaction limits, auditable action records, and fast credential or session revocation. The Connective Layer Is Now an Attack Surface The Model Context Protocol, or MCP, gives AI applications a standard way to discover and use external tools. The report is careful to say the protocol is not inherently unsafe. The concern is that it concentrates powerful capabilities behind an interface an agent can invoke. In the survey, 32.9% confirmed finding an unauthorized, shadow, or misconfigured MCP server in the past year, and 54.3% confirmed or suspected one. Salt Labs also reports detecting MCP-related infrastructure in 21.6% of customer environments in August 2026, up from 16.7% in January. The report itself cautions that the customer population grew between those measurements, so this is a change in detected prevalence rather than growth in a fixed group. The same restraint applies to the attack data. Salt Labs observed attacker activity on agentic-connected API paths in 26.3% of the environments where it looked, but calls the analysis experimental, limited, and directional. I would treat it as a signal that these endpoints are already on the attackers' radar, not as a market-wide rate. Separately, the broader telemetry covers 5,319,583 API endpoints and 104,339 attacker instances over twelve months. 95.8% of those attacker instances were authenticated. The report warns against assuming those are agents. The takeaway is narrower and still important: authentication alone does not establish trust. A Framework I Would Use: Sort Actions by Consequence This part is my analysis, not the report's. Do not treat every agent action as one risk class. I would sort them into three: Read. Retrieving information. Often fine to run autonomously with logging.Write. Changing a record, a configuration, or a permission. Needs policy checks tied to the resource and the sensitivity of the change.Destructive or external. Deleting data, moving money, altering access, or contacting a third party. Needs the strongest gate, which may mean human approval or hard transaction limits. Notice that the survey's own breakdown maps onto these tiers. External transactions, permission changes, deletions, and third-party contact are all in the top half of the list. A read-only assistant and a write-capable agent should never share the same trust assumptions just because they share a model. What I Would Do on Monday The report's recommendations point in a consistent direction, and I would compress them into five moves: Build a living inventory that maps agents, MCP servers, tools, APIs, and data flows together, not just a flat list of endpoints.Give each production agent its own non-human identity with narrow scope, a named owner, and credentials that can be revoked quickly.Put policy checks at the action boundary, before the high-impact call executes, instead of relying on detection after the fact.Preserve a correlated trail from the initiating instruction to the final state change, and aim to make reconstruction a minutes-long task.Measure the controls: scoped identity coverage, path trace coverage, time to reconstruct, time to contain, and how quickly unknown MCP servers are discovered. A Note on Sourcing This is a vendor survey. Salt Security sells agentic and API security products, and the report's methodology says it doesn't use a fixed respondent panel, so changes from the prior report are directional. Treat the figures as informed signal rather than audited fact. The two executive comments in the release reflect this vendor perspective. Salt CEO Roey Eliyahu said the data shows a gap "already producing real operational consequences." Yaniv Balmas, Salt's Head of Research, said the company's Manus research and the survey are "two views of the same problem." Per the release, Salt Labs showed that a single malicious email could hijack the Manus agentic platform and reach connected accounts, and that the platform's guardrail detected the attack but did not stop it before the malicious code ran. I have not independently verified that research, so I am attributing it to Salt. The Real Question The report closes on a test I find hard to improve: can your organization say what an agent did, why it was allowed, and whether you can stop it? Most cannot yet answer all three. The sensible response is not to slow agents down out of fear. It is to treat their authority as a privileged interface, engineered and monitored like every other one.

By Igboanugo David Ugochukwu DZone Core CORE
Batching Strategies: Throughput vs Latency in Practice
Batching Strategies: Throughput vs Latency in Practice

Production inference is fundamentally a scheduling problem. Once you've addressed serving architecture and memory, the next question isn’t whether the GPU can do the work; it's how to schedule it. That decision begins with understanding the workload: how requests arrive, how long they run, which are latency-sensitive, and which can tolerate delay. This is where many production deployments encounter their next engineering challenge. Serving architecture establishes how an inference system is organized. Memory management determines how efficiently it uses GPU memory. Batching answers a different question: How do you keep expensive GPUs doing useful work while still meeting latency service-level objectives (SLOs)? Production workloads introduce competing objectives that don't exist during experimentation. Production LLM systems serve requests that arrive unpredictably, vary dramatically in length, and compete for the same hardware resources. The engineering challenge isn’t batching requests together; it's deciding how work should be scheduled as those requests enter and leave the system. Production Traffic Is Inherently Uneven Most proof-of-concept environments present an idealized view of inference. Requests arrive at predictable intervals. Prompt lengths are similar. Response lengths are relatively consistent. Production looks nothing like that. Prompt lengths, output lengths, arrival patterns, and latency expectations differ. But production schedulers have to account for all of them simultaneously. That heterogeneity is what transforms batching from a simple grouping exercise into a scheduling problem. One user may ask a simple question that requires only a few tokens. Another may submit a lengthy document that requires a large context window and an extended response. Some requests are interactive and latency-sensitive. Others are background jobs that can tolerate additional delay. Treating all of those requests as if they were identical creates unnecessary inefficiencies. That is why batching strategies that work well during experimentation often become liabilities in production. Static Batching Breaks Under Real Workloads Static batching is straightforward: Collect a group of requests, execute them together, and wait until the batch finishes before beginning the next one. That approach works well for many traditional AI workloads because inputs generally require a similar amount of computation. Autoregressive generation behaves differently. Each request generates tokens at its own pace. Some complete almost immediately. Others continue generating for hundreds or even thousands of decoding iterations. The result is that the shortest requests spend much of their time waiting for the longest one to finish. This is the convoy effect. The GPU is effectively synchronized to the slowest request in the batch. The GPU is occupied, but completed or short-running requests cannot release their resources until the longest request in the batch finishes. As production workloads become more diverse, those idle cycles accumulate. Throughput falls, latency increases, and expensive GPU resources spend more time waiting than performing useful work. Bigger Batches Are Not Always Better The natural response is often to increase batch size. Larger batches generally improve GPU utilization, but they also introduce a tradeoff. Every request must wait until enough additional work arrives to fill the batch, increasing queueing delay before execution even begins. Once execution starts, larger batches can also increase Time Per Output Token (TPOT). A configuration that delivers acceptable TPOT at one batch size may exceed the application's latency SLO as the batch grows. Higher GPU utilization provides little benefit if response times no longer meet application requirements. This is the central balancing act of production inference. Higher throughput often comes at the cost of higher latency. The engineering challenge is determining where that operating point belongs. An internal document-processing pipeline may prioritize maximum throughput because latency is relatively unimportant. A customer-facing assistant may willingly sacrifice some throughput to preserve fast responses. Neither choice is universally correct. The workload determines the objective. The batching strategy should support it. Continuous Batching Changes the Scheduling Model Modern serving systems approach the problem differently. Rather than waiting for an entire batch to complete, continuous batching schedules work at each decode iteration. Finished requests leave immediately. New requests enter immediately. The scheduler is no longer managing batches. It is managing decoding iterations. Requests enter the batch as capacity becomes available. Completed requests leave immediately. New requests replace them without waiting for the entire batch to finish. This seemingly simple change fundamentally alters GPU utilization. Instead of waiting for the longest request to complete, the scheduler continuously replenishes the batch with new work. GPU utilization becomes constrained primarily by queue depth rather than by the slowest request in the system. The scheduler is no longer waiting for an entire batch to complete. It's continuously looking for the next unit of useful work. The objective shifts from building larger batches to keeping the GPU continuously productive. Long Prompts Introduce Another Challenge The prefill phase processes the entire prompt in a single forward pass, while the decode phase generates one token at a time. These phases place very different demands on the hardware. Prefill is compute-bound. Decode is memory-bandwidth-bound. Long prompts can monopolize GPU compute, delaying interactive requests that are already in the decode phase. Chunked prefill addresses this by breaking large prompts into smaller segments that can be interleaved with ongoing decode operations. Rather than allowing one long prefill operation to dominate the GPU, the resource scheduler alternates between prompt processing and token generation, allowing engineers to balance Time to First Token (TTFT) for new requests against Time Per Output Token (TPOT) for active ones. The result is a more balanced system. Time to First Token (TTFT) for new requests remains reasonable while Time Per Output Token (TPOT) for active requests stays within acceptable service-level objectives. Once again, the objective is balance — not maximization. Scheduling Becomes Policy As production systems mature, batching becomes less about grouping requests and more about deciding which work should execute next. Interactive applicationsBackground batch jobsHigh-priority usersLow-priority workloads Each may require different treatment. Some workloads don't require interactive latency at all. If a business process can tolerate scheduled execution, maximizing throughput may be the better engineering decision than minimizing response time. Modern serving systems increasingly make resource scheduling decisions at the token level rather than at the request level. GPU time becomes a shared resource allocated according to policy instead of simple arrival order. That policy also extends to admission control. Available GPU capacity is not the same thing as available latency headroom. Accepting every incoming request may maximize utilization for a short period, but it can also push latency beyond acceptable SLOs for every user in the system. Well-designed serving systems recognize that preserving predictable latency is often more valuable than accepting one additional request. In production, saying "not yet" is frequently better than saying "yes" to everyone. Throughput and Latency Are Negotiated — Not Maximized One theme runs consistently through every batching strategy. There is no universally optimal configuration. The appropriate batch size, scheduling policy, and admission thresholds all depend on the workload and the service-level objectives the application must satisfy. There is no universally optimal configuration because every production deployment is balancing a different set of constraints. A nightly batch pipeline should not be engineered like an interactive coding assistant. Likewise, a customer support chatbot should not inherit the scheduling strategy of an offline document-processing system simply because both happen to use the same foundation model. The model may remain unchanged. The serving behavior should not. The objective isn't maximum throughput. It's the highest sustainable throughput that still satisfies the application's latency SLOs. Looking Ahead Serving architecture organizes the inference system. Memory management ensures efficient GPU memory use. Batching strategies determine how available resources are converted into useful work. The final layer focuses on extracting even more performance from the same hardware. In the next article, we'll examine inference optimization techniques – including quantization, speculative decoding, FlashAttention, and distillation – and how carefully sequencing those optimizations can dramatically reduce cost and latency without changing the underlying model.

By Md Sharique
Why AI Agents Need a Shared Enterprise Ontology
Why AI Agents Need a Shared Enterprise Ontology

Agents Can Communicate, But Do They Understand Each Other? Two agents. Same customer ID. Different decisions. That is the semantic gap hiding inside most multi-agent enterprise deployments today — and protocols like MCP and A2A alone cannot close it (nor will they ever). AI agents are getting better at interacting through APIs, events, messages, and shared protocols. They can exchange data, invoke services, and coordinate tasks across enterprise systems. But communication doesn’t guarantee understanding. Imagine three agents dealing with the same customer request. One sees a customer as an account holder, another as a billing entity, and a third as a CRM contact. Data is exchanged, but each agent interprets it differently. This exposes a fundamental challenge in multi-agent enterprises: agents can exchange information without sharing the same meaning. Protocols define how information is exchanged. APIs define what data is exchanged. Neither defines what enterprise concepts such as customer, product, entitlement, incident, or approval actually mean. As organizations deploy specialized agents in sales, finance, ops, security, and engineering, semantic consistency is paramount. Agents need more than connectivity — they need a shared understanding of business concepts, relationships, and constraints. “Agent interoperability is not only a protocol problem; it is a semantic problem.” The Semantic Gap in Multi-Agent Enterprises In a multi-agent enterprise, different agents are built by different teams, trained on different data sets, connected to different systems, and designed around different business contexts. They may all exchange valid JSON messages, call the same APIs, or participate in the same workflow but still interpret the underlying business concepts differently. This is the semantic gap: what’s different between exchanging data and agreeing on what that data means? For example, the term customer may refer to a: CRM contact for a sales agentBilling account for a finance agentService subscriber for a support agentLegal entity for a compliance agent Similarly, priorities, incidents, owners, entitlements, or approvals may have different meanings in systems and domains. These differences are manageable when humans are involved because people infer context, ask clarifying questions, and reconcile ambiguity. Autonomous agents cannot do this reliably unless the semantics are explicitly represented. Without shared semantics, multi-agent systems can suffer from: Inconsistent interpretations of the same enterprise dataIncorrect agent-to-agent handoffsDuplicated or conflicting decisionsBrittle mappings between systemsGovernance rules that are applied differently across agents The challenge therefore moves beyond technical interoperability. Enterprises need semantic interoperability — a common model of concepts, relationships, constraints, and vocabulary that gives every participating agent the same frame of reference. That semantic foundation is provided by a shared enterprise ontology. What Is a Shared Enterprise Ontology? A shared enterprise ontology is a common semantic model that describes the concepts an enterprise uses (and how they are related to each other), as well as rules that give meaning to those concepts. It gives business knowledge a machine-readable format so that people, applications, and AI agents interpret enterprise information consistently. An ontology may define concepts such as: CustomerProductOrderServiceIncidentEntitlementEmployeeApproval More importantly, it defines how these concepts relate. For example: Customer → purchases → ProductCustomer → owns → AccountProduct → provides → ServiceIncident → affects → ServiceEmployee → approves → Request This is different from simply maintaining a common vocabulary. An ontology captures meaning, relationships, hierarchy, and constraints. A shared enterprise ontology thus becomes a semantic reference layer that agents can use to interpret data from different systems in the same way. Instead of each agent deciding what a customer, incident, or approval is, the enterprise defines those concepts once and reuses them across the enterprise. For multi-agent systems, this shared semantic model can become the common language that enables agents not only to exchange information but also to reason about it consistently. Why APIs, MCP, and A2A Are Not Enough on Their Own APIs, MCP, and A2A are examples of how interoperability problems are solved. Agents discover capabilities; they exchange messages; invoke tools; coordinate actions across systems. But they are more about connectivity and interaction than shared meaning. An API can have a field called customer_id. MCP can expose a tool to get customer data. An A2A interaction can send that information from one agent to another, but none of these mechanisms by themselves guarantees that every participating agent will interpret customer, account, service, or entitlement in the same way. This distinction matters. APIs specify how applications exchange data and invoke functions.MCP standardizes how models and agents access tools, resources, and context.A2A allows agents to communicate, delegate, and collaborate. These mechanisms provide technical interoperability, but semantic interoperability requires an additional layer: a common understanding of enterprise concepts and relationships. For example, two agents may exchange an incident object through an API or agent protocol, but one interprets an incident as a customer support ticket and the other an operational outage. Technically, they succeed in communication, but the decision made may still be wrong. An ontology for shared enterprise complements APIs, MCP, and A2A by specifying the semantic contract behind the information exchanged. In that model: APIs provide access.MCP provides tool and context interoperability.A2A provides agent collaboration.Ontology provides shared meaning. Together, these layers create a stronger foundation for reliable multi-agent enterprise systems. What Should an Agent-Aware Enterprise Ontology Describe? A traditional enterprise ontology describes business concepts (customers, products, services, orders, assets, and incidents). An agent-aware enterprise ontology should also go further by describing the agents that operate on those concepts. At minimum, it should capture five areas: Enterprise entities – customer, product, service, account, incident, policy, asset, employee.Relationships – owns, depends on, affects, approves, belongs to, consumes, manages.Agent capabilities – what an agent can search, analyze, create, modify, approve, or execute.Permissions and constraints – what an agent is allowed to access or change, under which conditions.Operational context – which system owns the data, its sensitivity, lifecycle state, provenance, and applicable governance rules. For example, the ontology could say that a Support Agent can read customer entitlement data; create an incident; recommend a resolution — but cannot approve a refund above some threshold. A Finance Agent can access billing records and authorize certain financial actions. This is what makes the ontology useful not only for understanding enterprise data but also for understanding who can act on that data, how they can act, and under what constraints. An agent-aware ontology can therefore answer questions like: What does this concept mean?Which agent owns this capability?What data can the agent access?Which actions are permitted?What policies apply before execution? This turns the ontology from a passive knowledge model into a semantic foundation for agent discovery, coordination, authorization, and governance. From Skill Discovery to Semantic Capability Discovery Most agent platforms can already discover skills or tools: search a catalog, inspect a description, and invoke a capability. The limitation is that skill discovery is usually done based on names, keywords, or interface descriptions. An agent may find a tool called create_ticket, but still not understand: What type of ticket it createsWhich business entity the ticket relates toWhat prerequisites applyWhat permissions are requiredWhether another capability is semantically equivalent This is where semantic capability discovery becomes important. Instead of asking only: “Which skill matches this request?” an agent can ask:“Which capability can perform this business action on this enterprise entity under these constraints?” For example, an ontology could describe that: RefundProcessingAgent → canPerform → IssueRefundIssueRefund → appliesTo → CustomerOrderIssueRefund → requires → ApprovedReturnIssueRefund → governedBy → RefundPolicy Now the agent isn’t finding a skill by name alone. It is finding a capability based on meaning, relationships, prerequisites, and policy context. This is especially useful when multiple agents expose overlapping capabilities (one agent may support refunds on retail orders, another on subscriptions, and another only for low-value transactions). Semantic metadata lets the orchestrating agent choose the right capability based on business context rather than just string matching. In this model, the ontology becomes a semantic capability graph connecting: Agent → Capability → Business Entity → Preconditions → Policies → Constraints This enables richer agent discovery, better routing, safer composition, and more reliable delegation across the enterprise. Ontology-Driven Agent Selection and Governance As enterprises deploy more specialized agents, choosing the right agent gets harder. A request may match several agents, but not every agent will have the same capability, authority, data access, or policy constraints. An enterprise ontology can make this selection more intelligent. Instead of routing a request based only on keywords or static configuration, an orchestrator can use semantic relationships such as: Agent → hasCapability → ApproveRefundApproveRefund → appliesTo → CustomerOrderAgent → authorizedFor → RegionCapability → constrainedBy → RefundPolicy When a task arrives, the system can evaluate not only which agent can perform it, but also: Whether the agent has the required capabilityWhether it can access the relevant enterprise dataWhether it is authorized for the requested actionWhich policies and constraints applyWhether human approval is required For example, two agents can both process refunds - one may be limited to transactions below a defined threshold, while another may handle high-value refunds but require managerial approval. The ontology provides the semantic context needed to route the request correctly. The same model can also support governance. Policies can be directly associated with business entities, capabilities, roles, and actions, so agents can reason about constraints before execution. This creates an ontology-driven decision flow: Request → Business Intent → Required Capability → Eligible Agents → Policy Evaluation → Selected Agent → Execution The result is more than smarter routing. It enables policy-aware, context-aware, and explainable agent selection across the enterprise. Building a Minimal Agent-Aware Enterprise Ontology AgentsCapabilitiesEnterprise entitiesPolicies and constraints Consider a simple refund-processing scenario. An enterprise has a support agent that can process refunds for customer orders, but that capability is governed by a refund policy. A minimal semantic model could look like this: This can be represented using RDF/OWL-style semantics. For example, using Turtle: Turtle @prefix ex: <http://example.com/enterprise#> ex:SupportAgent a ex:Agent ; ex:hasCapability ex:ProcessRefund ; ex:accesses ex:CustomerAccount ex:ProcessRefund a ex:Capability ; ex:appliesTo ex:CustomerOrder ; ex:governedBy ex:RefundPolicy . ex:RefundPolicy a ex:Policy ; ex:maxAutomaticRefund "500" Even this small ontology gives an orchestrating agent more information than a conventional tool catalog. Instead of discovering only process_refund(order_id), the agent can understand that the capability: Operates on a CustomerOrderIs provided by the SupportAgentDepends on access to customer informationIs governed by a specific refund policy The next step is to query the ontology. For example, an orchestrator could ask: SQL SELECT ?agent WHERE { ?agent ex:hasCapability ex:ProcessRefund . } The result identifies agents that semantically provide the required capability. A richer query could also include policy and business context: SQL SELECT ?agent ?policy WHERE { ?agent ex:hasCapability ?capability . ?capability ex:appliesTo ex:CustomerOrder . ?capability ex:governedBy ?policy . } This creates the foundation for semantic agent selection. The important point is that the ontology does not replace APIs, MCP tools, or agent protocols. It sits above them as a semantic decision layer. The ontology determines: What does the request mean?Which capability is required?Which agent provides it?Which enterprise entity is affected?Which policy applies? The execution layer can then use an API, MCP tool, or A2A interaction to perform the actual action. For a production environment, this minimal model can gradually expand to include concepts such as roles, data sensitivity, regions, approval thresholds, provenance, dependencies, risk levels, and human-approval requirements. The key is to start small. A handful of well-defined enterprise concepts and relationships can already move agent orchestration from simple tool matching toward semantic, policy-aware capability discovery. Where This Architecture Fits in the Emerging Agent Stack The ontology-driven architecture fits between the agent reasoning layer and the execution layer of the emerging enterprise agent stack. A typical enterprise agent stack may include: User or application layer – where requests originateAgent/orchestration layer – interprets intent and coordinates workSemantic layer – maps intent to enterprise concepts, capabilities, policies, and eligible agentsInteraction layer – MCP, APIs, A2A, events, and messagingEnterprise systems layer – CRM, ERP, ITSM, data platforms, and internal services The shared enterprise ontology belongs primarily in the semantic layer. Its role is not to replace the LLM, agent framework, MCP server, API gateway, or A2A protocol. Instead, it provides the semantic context needed before those components are used. This separation is important because each layer solves a different problem. The reasoning layer determines what the user is asking.The ontology layer determines what that request means within the enterprise.The orchestration layer determines which agent should handle it.The interaction layer determines how the selected agent or tool is invoked.The enterprise systems layer performs or records the actual business action. As agent ecosystems become more distributed, this semantic layer can act as connective tissue across otherwise independent agent platforms. Different agents may use different models, frameworks, protocols, or runtime environments while still relying on the same enterprise definitions of capabilities, entities, and policies. The architecture therefore adds a missing layer to the emerging agent stack: semantic interoperability between reasoning and execution. Challenges: Ontology Evolution, Ownership, Federation, and Governance A shared enterprise ontology improves semantic interoperability but also brings its own operational and governance problems. Enterprise concepts are not fixed: products change, organizational structures evolve, regulations shift, and new agents bring new capabilities; the ontology must therefore evolve without breaking existing consumers. Ontology Evolution In a federated ontology landscape, a change in one domain propagates to the entire semantic layer. Changing CustomerAccount in the Customer/CRM ontology, tightening the Entitlement definition in the Product ontology, or adding a new relationship between Incident and Risk in the IT and Operations domain can affect every agent that reasons over those concepts (sometimes not immediately visible). A database schema change usually only affects one system, whereas an ontology change can impact how a sales agent qualifies a lead, how a support agent resolves a ticket, how a finance agent authorizes a payment, and how a compliance agent evaluates a policy, all at the same time. The blast radius is wide because the semantic layer is shared. Ontology evolution therefore needs practices borrowed from API lifecycle management: Versioning – URI-based version identifiers on classes and relationships (for example, ex:v2/CustomerAccount) so that agents can declare which ontology version they depend on.Backward compatibility – additive changes are preferred; breaking changes require a deprecation period with the old and new definitions coexisting.Deprecation policies – a defined timeline for retiring concepts, with explicit successor mappings so consuming agents can migrate incrementally.Change impact analysis – before publishing a change, tooling should identify which agents, tools, and downstream applications reference the affected concepts.Validation before rollout – semantic regression tests that verify existing agent queries and capability graphs still resolve correctly against the new version. Agents should declare which ontology version they are using, and orchestrators should be able to route requests to agents that share a compatible semantic baseline. This prevents a situation where two agents with different ontology versions interpret the same concept differently — which is precisely the problem the ontology was introduced to solve. Ownership A central question is: who owns the meaning of enterprise concepts? The answer is rarely the team that builds the ontology infrastructure. A platform or architecture team may maintain tooling, graph store, versioning pipeline, and publishing process — but it shouldn’t define what Customer, Risk, Incident, Entitlement, or Approval mean independently of those concepts. Those definitions carry business, legal, and operational weight. Semantic ownership should be closer to the business domain. Customer/CRM ontology should belong to teams that run CRM processes and understand what a customer relationship means commercially; Finance ontology should be owned by finance and accounting because they know the difference between an Invoice, Payment, Cost Center, and Financial Account; Security ontology (Identity, Role, Permission, Policy, and Risk) should belong to security teams who understand the compliance implications of each concept. This model (central semantic governance with distributed domain ownership) is how platform engineering works at scale. The platform team sets standards, tooling, and alignment rules across domains. Domain teams set meaning within their area. Neither can override the other unilaterally. In practice, this means having ownership metadata on every ontology concept: who owns it (team), who is the subject-matter expert, and which review process applies when that definition needs to change. If not, the ontology becomes either a bottleneck controlled by one central team or an inconsistent patchwork where every team modifies concepts without coordination. Federation Trying to force all of this into one monolithic ontology isn’t practical. Governance bottleneck; slows down domain teams; model is too abstract to be useful for any specific domain. The diagram above shows a scalable alternative: federated ontology design. Each domain has its own ontology (Customer/CRM, Finance, Product, IT and Operations, Security and HR) — they have full autonomy over the concepts, relationships, and terminology in that domain. Ontologies for each domain link to an Enterprise Ontology Core shared by all domains via explicit semantic mappings and alignment relationships. The core contains cross-domain concepts, shared vocabularies, and governance and versioning rules that make federation work. This architecture also extends outward in two directions. On one side, the enterprise core aligns with external industry ontologies — schema.org for general web semantics, GS1 for product and supply chain standards, FIBO for financial industry terminology, SNOMED CT for healthcare — allowing the enterprise to adopt established standards rather than reinventing definitions. On the other side, partner and ecosystem ontologies for suppliers, regulatory bodies, and industry-specific frameworks can federate with the core through controlled extension points. The goal is not to eliminate domain-specific meaning. It is to make the relationships between those meanings explicit and machine-readable, so that an agent operating in the Finance domain and an agent operating in the Customer domain can each reason within their own semantic context while still communicating consistently when their work intersects. Federation also means that new domains can be onboarded incrementally. A new AI agent introduced for HR or procurement does not require a redesign of the entire ontology. It connects through the same alignment and mapping pattern, inheriting cross-domain concepts while adding its own domain vocabulary. Governance Because AI agents use ontology definitions to make autonomous operational decisions, semantic changes are no longer just documentation updates — they are configuration changes with real business consequences. Changing the definition of Entitlement may cause a support agent to deny services it should approve. Altering the Policy concept may cause a finance agent to bypass a control it previously enforced. The ontology is live operational infrastructure. Governance must therefore be treated with the same rigor applied to production software releases. At minimum, it should define: Who can propose changes – any domain team can propose additions or modifications within their domain, but cross-domain changes require joint review.Who approves semantic changes – changes to core enterprise concepts should require approval from the relevant domain owners and a central semantic governance board.How conflicts between domains are resolved – when two domain teams define the same concept differently (for example, both Finance and CRM define Account), there must be a defined arbitration process that results in either a canonical definition or an explicit mapping.How provenance is recorded – every concept should carry metadata about who introduced it, when, why, and which version it appeared in, so that an audit trail is always available.How policy-related concepts are reviewed – concepts that directly govern agent behavior, such as approval thresholds, permission levels, and compliance rules, should require review by legal, compliance, or risk teams before they are published.How changes are tested against existing agent workflows – before a semantic change is released, it should be validated against a test suite of representative agent queries and orchestration flows to confirm that existing behavior is not unintentionally altered. For high-impact concepts, ontology updates should require the same level of review as a production policy change or a regulated configuration update. The bar is not arbitrary: if an agent can take a financial action, restrict access, or escalate an incident based on an ontology definition, then that definition carries the same operational weight as the code or policy that governs the same action. Ultimately, the challenge is not just building a shared ontology. It is maintaining a trusted semantic contract across teams, systems, and agents as the enterprise continuously changes. The federated architecture distributes that responsibility appropriately — each domain team owns what they understand, the core team maintains coherence, and governance ensures that changes are deliberate, reversible, and traceable. “A shared ontology is only valuable if its meaning remains governed, traceable, and trustworthy as the enterprise evolves.” Conclusion In the multi-agent enterprise, communication is only the first step. True collaboration requires a shared understanding of business meaning. Protocols connect agents; ontologies align them. As AI ecosystems grow, semantic interoperability will become as important as technical interoperability. The challenge will no longer be whether agents can communicate, but whether they understand enterprise concepts well enough to collaborate safely, consistently, and effectively. A practical starting point is simple: model three things, your key business entities, the agents that operate on them, and the policies that govern those interactions. The ontology can evolve incrementally as the agent ecosystem grows. The future of enterprise AI will depend not only on smarter agents, but on agents that share a common understanding of the enterprise they serve.

By Josephine Eskaline Joyce, Ph.D DZone Core CORE
Adding Graph Retrieval to a RAG Pipeline With Python
Adding Graph Retrieval to a RAG Pipeline With Python

The majority of retrieval-augmented generation (RAG) examples start as follows: document segmentation; create embedding representations for segmented document sections ("chunks"); store those representations in a vector database and use them to "retrieve" the "best matching" document section(s) for any user-inputted search query. That is a good starting point. However, there is one significant limitation to the process described above: not all questions relate solely to similarity. Some questions relate to relationships. For example: Which team owns the API that Checkout Service uses? While a vector search system could potentially identify documents related to "Checkout Service," "Payment API," and "Platform Team," the critical piece of information is the relationship between these concepts: Markdown Checkout Service --DEPENDS ON--> Payment API Platform Team --OWNS--> Payment API This is when graph retrieval becomes a value-added element. Unlike retrieving only documents based on similarity to a query, a graph retrieval layer can retrieve connected Facts from a graph, providing relationship-aware context to a large language model (LLM) while allowing the LLM to generate the final answer. In other words, instead of simply providing additional context to an LLM in terms of a specific set of retrieved documents, a graph retrieval layer would be able to provide structured context. In this tutorial, we will develop a basic graph retrieval layer to enhance a RAG pipeline utilizing Python and NetworkX. We will load relationship triples from a JSON File, build a directed graph, retrieve the local neighborhood of any entity matched by the retrieval layer, and convert that graph-based context into a format suitable for an LLM Prompt. Why Graph Retrieval Helps Most traditional RAG methods are effective for questions that have answers composed within a couple of data "chunks." Examples include: What database does Payment API utilize? As an example, if you have documentation that states, "The Payment API utilizes PostgreSQL," then a vector search should normally identify it. However, as soon as you are looking for information about related facts (i.e., multiple connected pieces of fact), plain similarity search may not provide sufficient results: Who owns the API that the Checkout Service relies upon? In order to determine who owns the API that the Checkout Service relies upon, you need to perform at least two link traversals: Checkout Service -> Payment APIPlatform Team -> Payment API Since this creates a relationship map (a graph), systems, teams, APIs, and databases all represent nodes in the graph, while their relationships all represent the edges in the graph. As long as this structure is in place, retrieval can follow edges (relationships) rather than simply rely on semantic similarities. This does not mean that graph retrieval replaces vector search completely. A hybrid approach has been found to be more successful in most production environments; specifically, the vector search identifies relevant text, while the graph retrieval identifies relevant relationships among those texts, and ultimately the final answer will be determined using both. Therefore, our main emphasis in this article will be solely on the graph retrieval layer. What We Are Building We are creating a short Python application: Loading data (relationship triples) from file "triples.json".Building a directional graph using NetworkX.Identifying all entities mentioned within the user's input query.Retrieving related graph information.Converting that related information to form context for the LLM prompt.Writing the processed contextual information to "graph_context.json." Output will appear as follows: JSON { "question": "which team is responsible for owning the api Checkout Service depends on?", "context": [ "Checkout Service depends_on payment api.", "Platform Team OWNS Payment API." ] } Then you could pass that created contextual information into an LLM prompt portion of a RAG prompt. Project Setup Create a new project folder: Shell mkdir graph-retrieval-rag cd graph-retrieval-rag Create a requirements.txt file: Plain Text networkx==3.3 Install the dependency: Shell pip install -r requirements.txt Create a file named 'triples.json': JSON [ { "subject": "Checkout Service", "relation": "DEPENDS_ON", "object": "Payment API", "source_text": "Checkout Service depends on Payment API during payment authorization." }, { "subject": "Payment API", "relation": "USES", "object": "PostgreSQL", "source_text": "Payment API uses PostgreSQL for transaction metadata." }, { "subject": "Platform Team", "relation": "OWNS", "object": "Payment API", "source_text": "Platform Team owns Payment API." }, { "subject": "Recommendation Service", "relation": "CALLS", "object": "Catalog API", "source_text": "Recommendation Service calls Catalog API to retrieve product details." }, { "subject": "Catalog API", "relation": "USES", "object": "Elasticsearch", "source_text": "Catalog API uses Elasticsearch for product search." }, { "subject": "Search Team", "relation": "OWNS", "object": "Catalog API", "source_text": "Search Team owns Catalog API." } ] This file is intentionally small. In a real system, these triples could come from entity extraction, service catalogs, architecture documents, source code metadata, or cloud inventory. Step 1: Load Relationship Triples Create a file named graph_retriever.py. Python import json def load_triples(path): with open(path, "r", encoding="utf-8") as file: return json.load(file) Each triple has four fields: Plain Text subject relation object source_text The source_text field matters because graph context should remain traceable. When the model uses a retrieved relationship, the system should know where that relationship came from. Step 2: Build a Directed Graph Next, we will create a graph from these triples by importing the NetworkX library for Python, which can create different graph types (for example, directed or undirected). Python import networkx as nx def build_graph(triples): graph = nx.DiGraph() for triple in triples: subject = triple["subject"] object_ = triple["object"] relation = triple["relation"] graph.add_node(subject) graph.add_node(object_) graph.add_edge( subject, object_, relation=relation, source_text=triple["source_text"], ) return graph A directed graph is important because relationship direction changes meaning. This: Plain Text Checkout Service --DEPENDS_ON--> Payment API does not mean the same thing as: Plain Text Payment API --DEPENDS_ON--> Checkout Service Direction matters for dependency analysis, ownership lookup, impact analysis, and many GraphRAG workflows. Step 3: Find Query Entities We're going to find entities mentioned in a question using simple string searching as the means of finding them. Python def find_query_entities(graph, question): question_lower = question.lower() matches = [] for node in graph.nodes: if node.lower() in question_lower: matches.append(node) return matches The code here does not represent a full NLP solution. This is simply a straightforward baseline. In production, you would probably want to do things like aliasing, entity linking, fuzzy matching, etc., or train your own model. In order to normalize the way that a question is phrased versus how something is named in the graph. For instance, "checkout" might be used to ask about the "Checkout Service. Step 4: Retrieve a Graph Neighborhood After identifying the graph element that will answer a question, identify all other elements connected to it. One method to do this would be to gather together both outgoing and incoming edges at each identified node. This could be done with the following code snippet: Python def retrieve_neighborhood(graph, seed_entities, max_hops=2): visited_nodes = set(seed_entities) frontier = set(seed_entities) retrieved_edges = [] for _ in range(max_hops): next_frontier = set() for node in frontier: for neighbor in graph.successors(node): edge_data = graph.get_edge_data(node, neighbor) retrieved_edges.append((node, edge_data["relation"], neighbor, edge_data)) next_frontier.add(neighbor) for neighbor in graph.predecessors(node): edge_data = graph.get_edge_data(neighbor, node) retrieved_edges.append((neighbor, edge_data["relation"], node, edge_data)) next_frontier.add(neighbor) frontier = next_frontier - visited_nodes visited_nodes.update(next_frontier) return deduplicate_edges(retrieved_edges) # Adding a helper function to remove duplicate edges: def deduplicate_edges(edges): seen = set() unique_edges = [] for source, relation, target, edge_data in edges: key = (source, relation, target) if key not in seen: seen.add(key) unique_edges.append((source, relation, target, edge_data)) return unique_edges The max_hops parameter controls how far retrieval travels from the original query entity. For example: Plain Text max_hops=1 retrieves immediate neighbors. max_hops=2 retrieves neighbors of neighbors. While higher values give you a larger amount of additional knowledge about your subject matter, this may also introduce a lot of "noise" into your results. Step 5: Convert Graph Results Into LLM Context The retrieved graph edges are structured data. Before sending them to an LLM, convert them into short, readable facts. Python def format_edges_as_context(edges): context = [] for source, relation, target, edge_data in edges: context.append( { "fact": f"{source} {relation} {target}.", "source_text": edge_data["source_text"], } ) return context This gives the prompt two useful forms of evidence: A normalized graph fact.The original source sentence. That makes the final answer easier to debug and easier to cite. Step 6: Build a RAG Prompt Now create a simple prompt builder. Python def build_prompt(question, graph_context): context_lines = [] for item in graph_context: context_lines.append(f"- {item['fact']} Source: {item['source_text']}") context_text = "\n".join(context_lines) return f""" You are answering a question using graph-retrieved context. Use only the facts provided in the context. If the context does not contain enough information, say so. Question: {question} Context: {context_text} Answer: """.strip() This prompt is intentionally restrictive. The model should use the source instead of guessing. A good production application would also include a format for citations, rules for how to write responses, and fallback behavior. Complete Example Here is the full code: Python import json import networkx as nx def load_triples(path): with open(path, "r", encoding="utf-8") as file: return json.load(file) def build_graph(triples): graph = nx.DiGraph() for triple in triples: subject = triple["subject"] object_ = triple["object"] relation = triple["relation"] graph.add_node(subject) graph.add_node(object_) graph.add_edge( subject, object_, relation=relation, source_text=triple["source_text"], ) return graph def find_query_entities(graph, question): question_lower = question.lower() matches = [] for node in graph.nodes: if node.lower() in question_lower: matches.append(node) return matches def retrieve_neighborhood(graph, seed_entities, max_hops=2): visited_nodes = set(seed_entities) frontier = set(seed_entities) retrieved_edges = [] for _ in range(max_hops): next_frontier = set() for node in frontier: for neighbor in graph.successors(node): edge_data = graph.get_edge_data(node, neighbor) retrieved_edges.append((node, edge_data["relation"], neighbor, edge_data)) next_frontier.add(neighbor) for neighbor in graph.predecessors(node): edge_data = graph.get_edge_data(neighbor, node) retrieved_edges.append((neighbor, edge_data["relation"], node, edge_data)) next_frontier.add(neighbor) frontier = next_frontier - visited_nodes visited_nodes.update(next_frontier) return deduplicate_edges(retrieved_edges) def deduplicate_edges(edges): seen = set() unique_edges = [] for source, relation, target, edge_data in edges: key = (source, relation, target) if key not in seen: seen.add(key) unique_edges.append((source, relation, target, edge_data)) return unique_edges def format_edges_as_context(edges): context = [] for source, relation, target, edge_data in edges: context.append( { "fact": f"{source} {relation} {target}.", "source_text": edge_data["source_text"], } ) return context def build_prompt(question, graph_context): context_lines = [] for item in graph_context: context_lines.append(f"- {item['fact']} Source: {item['source_text']}") context_text = "\n".join(context_lines) return f""" You are answering a question using graph-retrieved context. Use only the facts provided in the context. If the context does not contain enough information, say so. Question: {question} Context: {context_text} Answer: """.strip() def write_json(path, data): with open(path, "w", encoding="utf-8") as file: json.dump(data, file, indent=2) if __name__ == "__main__": question = "Which team owns the API that Checkout Service depends on?" triples = load_triples("triples.json") graph = build_graph(triples) seed_entities = find_query_entities(graph, question) if not seed_entities: print("No matching graph entities found in the question.") raise SystemExit(0) retrieved_edges = retrieve_neighborhood(graph, seed_entities, max_hops=2) graph_context = format_edges_as_context(retrieved_edges) prompt = build_prompt(question, graph_context) result = { "question": question, "seed_entities": seed_entities, "graph_context": graph_context, "prompt": prompt, } write_json("graph_context.json", result) print("Seed entities:") print(seed_entities) print("\nGraph context:") for item in graph_context: print("-", item["fact"]) print("\nPrompt:") print(prompt) Run it: Python python graph_retriever.py Expected output: Python Seed entities: ['Checkout Service'] Graph context: - Checkout Service DEPENDS_ON Payment API. - Payment API USES PostgreSQL. - Platform Team OWNS Payment API. Prompt: You are answering a question using graph-retrieved context. Use only the facts provided in the context. If the context does not contain enough information, say so. Question: Which team owns the API that Checkout Service depends on? Context: - Checkout Service DEPENDS_ON Payment API. Source: Checkout Service depends on Payment API during payment authorization. - Payment API USES PostgreSQL. Source: Payment API uses PostgreSQL for transaction metadata. - Platform Team OWNS Payment API. Source: Platform Team owns Payment API. Answer: The answer is now straightforward: Plain Text Platform Team owns Payment API, which Checkout Service depends on. The important part is not that an LLM can phrase the answer. The important part is that retrieval found the connected facts needed to support it. What This Adds to a RAG Pipeline A standard RAG pipeline often looks like this: Markdown Documents | Chunking | Embeddings | Vector Search | LLM A graph-enhanced pipeline adds another retrieval path: Markdown Question | Query entity detection | Graph neighborhood retrieval | Graph context formatting | LLM In a hybrid system, both paths can work together: Markdown Question | |---- Vector search -> relevant text chunks | |---- Graph search -> connected facts | Combined context | LLM This is useful because vector search and graph retrieval solve different problems. Vector search is good at finding semantically similar text. Graph retrieval is good at following explicit relationships. Production Considerations The graph retrieval layer used in this example is very rudimentary. A production-quality implementation will have many additional "guardrails." Normalized entities are necessary for performing entity matching. Exact string matches will miss most common aliases (i.e., checkout, checkout-service, etc.); however, production-quality implementations will use canonical IDs/aliases/entity linking. Graph retrieval has limits. While there is no limit to how large a graph can grow in terms of returned context, returning too much context can be detrimental. To limit the amount of context returned, implement boundaries, including but not limited to hop count, edge type, node type, confidence value, and source data freshness. All relationships in the graph are not equal in reliability. For example, a dependency established by a service catalog entry may be a more reliable relationship than a dependency inferred from an older document. Therefore, store your confidence level, timestamp, and other source metadata values along with every edge. Not all relationships are equally reliable. Contextual information, in addition to just what was retrieved from the graph, should also contain evidence that supports or refutes the answer. As a result of providing evidence with contextual information, when someone reviews your answer, they will be able to easily verify the answer, and if something does go wrong during development, it will make it easier to debug. Hybrid approaches are best suited for using graph retrieval. While graph retrieval can help the model understand why certain pieces of information relate to each other, document chunks can provide much more detail about those related pieces. When retrieving both types of information, the model will likely receive more complete contextual information. Evaluation is mandatory. You will need to create realistic test questions and determine if the sub-graph retrieved from the database includes enough factual information for answering those test questions. Never assume that graph retrieval will improve performance unless you measure it. Key Takeaways Graph retrieval adds relational contextual knowledge to a RAG framework. A simple directed graph can answer many complex questions involving multi-step logic that would be difficult to accomplish with plain similarity-based search. One key design decision in developing an effective graph-retrieval system is what determines the success of the retrieval layer: does it identify the correct entities and their associated relationships? Graph retrieval works well when the question involves dependency, ownership, impact assessment, lineage, and/or multi-step reasoning. In addition to graph retrieval, build a production-quality retrieval system that includes source tracking, entity normalization, confidence scoring, and evaluation. Try It Yourself Add these triples to triples.json JSON { "subject": "Billing Worker", "relation": "PUBLISHES_TO", "object": "Kafka", "source_text": "Billing Worker publishes payment events to Kafka." }, { "subject": "Data Platform Team", "relation": "OWNS", "object": "Kafka", "source_text": "Data Platform Team owns Kafka." } Then change the question to: Plain Text Which team owns the system that Billing Worker publishes events to? Your goal is to retrieve: Plain Text Billing Worker PUBLISHES_TO Kafka. Data Platform Team OWNS Kafka. Once that works, try lowering max_hops from 2 to 1 and compare the retrieved context. This is a simple way to see why hop count matters in graph retrieval.

By Sriharsha Makineni

Monthly Top Integration Experts

expert thumbnail

John Vester

Senior Staff Engineer,
Marqeta

IT professional with 30+ years expertise in app design and architecture, feature development, and project and team management. Currently focusing on establishing resilient cloud-based services running across multiple regions and zones. Additional expertise architecting (Spring Boot) Java and .NET APIs against leading client frameworks, CRM design, and Salesforce integration.
expert thumbnail

Gunter Rotsaert

Software Architect / Requirements Engineer,
ICT TriOpSys

Gunter is a Software Architect and Requirements Engineer with over 25 years of experience in software engineering. Since 2005, he is developing mission-critical software systems via his employer ICT TriOpSys. Developing mission-critical software requires the highest standards in quality and security, which is an area in which Gunter has extensive experience. Since a couple of years, Gunter has a great interest in using AI in order to support the software engineering workflow. He enjoys sharing his knowledge and does so through blogging, technical workshops, conference talks and presentations for colleagues and the wider developer community. When he's not writing software or speaking about it, you'll find him playing slide trombone in the horn section of a funk, disco, and soul band.
expert thumbnail

Thomas Jardinet

IT Architect,
Rhapsodies Conseil

As an IT Architect with strong experience in Integration topics (with multiple contributions for Dzone Tech and Ref Cards), I accompany business projects in defining their architectures, whether functional, application or technical, by studying with them the best path. I also have more than I also accompany them in the organizational side, and above all I seek intellectual and human exchange. I am also a supporter of flattened organizations, as I think it greatly improves productivity, robustness, and resilience of companies

The Latest Integration Topics

article thumbnail
Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
Google Cloud Pub/Sub does in one service what AWS splits across SNS and SQS. MultiCloudJ gives both a single Java interface.
November 27, 2026
by Sandeep Pal DZone Core CORE
· 738 Views · 1 Like
article thumbnail
Passwordless Image Pulls in Kubernetes With ServiceAccount Tokens and a Credential Provider
The kubelet can hand a pod's ServiceAccount token to a plugin that swaps it for short-lived, read-only registry access. No imagePullSecrets.
November 27, 2026
by Mikhail Marchenko
· 677 Views
article thumbnail
Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo
The available alternatives of the @Sql Spring Data annotation for MongoDB in Java. Jamolingo as the closest solution for the @Sql experience.
November 26, 2026
by Szymon Tarnowski DZone Core CORE
· 961 Views · 1 Like
article thumbnail
Function Calling: Responses API vs Chat Completions
A wire-level comparison of function definitions, call IDs, result messages, streaming arguments, and safe tool execution across the Responses API and Chat Completions.
November 26, 2026
by Magnus Modelflare
· 634 Views
article thumbnail
Zero Trust for Agents: A New Lens to Secure Agents
The session was the right unit of risk when the subject was a person. For agents it is the wrong one, and two existing standards already point to the fix.
November 25, 2026
by Krishna Sunkavalli
· 1,127 Views · 1 Like
article thumbnail
Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API
Enable OpenAI's hosted Code Interpreter in Spring AI via the Responses API, then trace a real request as the model writes and runs Python server-side.
November 25, 2026
by Horatiu Dan DZone Core CORE
· 882 Views · 3 Likes
article thumbnail
Reusable Operational Playbooks With Agent Skills
Agent Skill enables engineers to follow consistent operational playbooks without manual copying and establishes a clear boundary.
November 24, 2026
by Daniel Oh DZone Core CORE
· 927 Views · 1 Like
article thumbnail
Building Enterprise Desktop, Web, Mobile, and Docker Applications From One Shared Platform
This article presents a reference architecture for building desktop, web, mobile, service, and containerized applications around a shared platform core.
November 23, 2026
by Dariusz Małyszko
· 840 Views
article thumbnail
Migrating From the OpenAI API to vLLM: Configure It Right
Pointing an OpenAI client at vLLM takes three code changes. Tool calling, structured output, context length and reasoning need server flags. Here they are.
November 23, 2026
by Matt Sarrel
· 768 Views · 1 Like
article thumbnail
Securing AI Agents in Production: A Developer’s Guide To Prompt Injection, RAG Leaks, and Tool Abuse
Learn how to secure AI agents in production against prompt injection, RAG data leaks, and tool abuse with practical controls, access policies, and monitoring.
November 18, 2026
by Paresh Sagar
· 1,448 Views · 1 Like
article thumbnail
Using Middleware in LangChain: Recovering From Tool Failures
LangChain Middleware provides ways to recover from Tool Failures. This article helps in understanding how to use ToolRetryMiddleware and @wrap_tool_call to handle errors.
November 17, 2026
by Ruchi Saini
· 1,180 Views · 4 Likes
article thumbnail
The Rise of the Unsanctioned Agent Swarm
Learn how to detect and secure shadow AI agents using zero-trust API gateway interceptors, non-human identities, scope enforcement, and rate limiting.
November 17, 2026
by Nikita Kothari
· 1,250 Views
article thumbnail
Choosing a BBD Framework
Learn how to choose a behavior-driven development framework, compare Cucumber, Reqnroll, Behave, and Godog, and avoid common BDD mistakes teams make.
November 13, 2026
by Himanshu Mandhyan
· 1,239 Views · 2 Likes
article thumbnail
Persisting Cookies Across JAX-WS Service Calls Using a Custom SOAP Handler
A custom SOAP handler preserves JAX-WS session cookies across calls without JVM-wide state, using ThreadLocal isolation and explicit cleanup to prevent session leaks.
November 12, 2026
by Vishal Rameshchandra Shah
· 1,333 Views
article thumbnail
Building Multi-Rail Payment Failover to Stop Latency Spikes and Double Debits
Resilient multi-rail payment routing using real-time latency scoring, distributed Redis mutex locks, and strict void-on-timeout controls.
November 9, 2026
by Irfan Syed Ahmed
· 1,128 Views · 2 Likes
article thumbnail
GET, POST, PUT, DELETE: Choosing HTTP Verbs in a Real .NET Core Web API, Not Just by the Textbook
Learn how to choose HTTP verbs in ASP.NET Core Web API, including POST-based soft deletes, batch operations, Angular integration, and idempotency.
November 5, 2026
by Dhana PAMULA
· 1,271 Views · 1 Like
article thumbnail
Your Event Storming Is Not Your Software Design
Explore how EventStorming supports software design decisions around ownership, contracts, coupling, coordination, and failure handling.
November 4, 2026
by Alireza Rahmani Khalili DZone Core CORE
· 1,484 Views · 1 Like
article thumbnail
Delegated Transport, Forked Authorization: Where Chat and AI-Agent Integrations Actually Break
A Python simulation exposes authorization gaps in third-party chat integrations, from delayed access revocation to AI agent misuse, and tests controls to prevent them.
November 2, 2026
by Igboanugo David Ugochukwu DZone Core CORE
· 1,019 Views · 1 Like
article thumbnail
A Non-Expiring AKS Deployment Token Could Read Secrets Across Three Namespaces
Learn how to secure Kubernetes Secrets by replacing long-lived service account tokens, tightening RBAC permissions, and improving Azure Key Vault integration.
November 2, 2026
by Ahmed Tariq
· 1,157 Views · 1 Like
article thumbnail
How To Build a Scalable SaaS Product Architecture
Start with a modular monolith, enforce tenant isolation, and build in security early. Scale infrastructure as demand grows instead of adding unnecessary complexity.
November 2, 2026
by Megha Verma
· 1,243 Views · 1 Like
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×