<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chamindu Udakara on Medium]]></title>
        <description><![CDATA[Stories by Chamindu Udakara on Medium]]></description>
        <link>https://medium.com/@cudakara?source=rss-3a99f0885f95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LEPnBjMreqwh8iS44HNz8w.jpeg</url>
            <title>Stories by Chamindu Udakara on Medium</title>
            <link>https://medium.com/@cudakara?source=rss-3a99f0885f95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:19:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cudakara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[One Agent, Many Hats: Persona-Scoped AI Assistants on AWS AgentCore]]></title>
            <link>https://cudakara.medium.com/one-agent-many-hats-persona-scoped-ai-assistants-on-aws-agentcore-9ae59f1cf27d?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ae59f1cf27d</guid>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[llm-chatbot]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 18:17:40 GMT</pubDate>
            <atom:updated>2026-11-22T18:25:18.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnV57IlxPArfrE-9BqzkAw.jpeg" /></figure><h4>Persona-scoped AI support assistants on AWS AgentCore: architecture, security, scale, and a budget that fits on a napkin</h4><blockquote><strong><em>TL;DR</em></strong><em> An AI assistant for internal questions is easy to demo and hard to run for more than one team. This is how mine grew from a stateless proof of concept into persona-scoped agents on AWS AgentCore: one Python agent, deployed once per team, each copy with its own prompt, gateway, IAM role, budget and file of hints. The model never touches a data store. It calls the APIs and MCP servers the company already trusts, read-only by default, and reaches private systems through VPC Lattice. Cost stays visible per persona through tagged inference profiles, AWS Budgets and an optional kill switch. Along the way: why I chose my own agent over the managed harness, why hints beat a longer prompt, and what I’d do differently. Every snippet links to a companion repo you can test offline.</em></blockquote><p>Every engineering team has a Slack channel like this. Someone from an operations team asks why an item is stuck. Someone else asks whether last night’s export finished. Then the same question again, phrased differently, from a different person, an hour later.</p><p>None of these questions are hard. Most of them are answered by running the same few lookups and translating the result into plain language. But each one costs an engineer a context switch, and the ones that wait too long turn into escalations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4HmoFdba8bBhFBNcMSE4A.png" /><figcaption>Problem at hand</figcaption></figure><p>So I designed an assistant to take that first pass. This is how it grew from a proof of concept inside an existing backend service into a set of persona-scoped agents on AWS AgentCore, each with its own prompt, its own tools, its own permissions and its own budget. It covers the architecture, the security model, how it scales, what it costs, and where I want to take it next.</p><p>The short version: the questions that reached an engineer dropped by roughly four in five, and the feedback from the teams using it was good. Here&#39;s how it got there.</p><p>Every snippet below comes from a small <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots">companion repo</a> that you can clone and test without an AWS account.</p><p>The main lesson fits in one sentence:</p><blockquote><strong><em>A persona is not a prompt. It’s a security boundary, a cost boundary and a set of tools, and the cheapest place to enforce all three is infrastructure, not code.</em></strong></blockquote><h3>Part 1: Three ways to answer a question</h3><p>Before writing any code, I looked at how larger companies automate their support and call-center questions. Three patterns kept coming up:</p><ul><li><strong>Let the model write the query.</strong> Give the LLM the schema and let it generate database queries. Flexible, and terrifying. My honest trust in an LLM writing and running queries against production was around 60%. That’s not a number you want anywhere near customer data.</li><li><strong>Classic conditional code.</strong> A decision tree for every question type. Safe and predictable, and it never ends: every new question is a new branch.</li><li><strong>Retrieval-augmented generation (RAG).</strong> Great for documents, but the answers I needed live in a database that changes every few minutes, not in a knowledge base.</li></ul><p>I went with a hybrid. <strong>The model never touches the database.</strong> It maps a natural-language question onto a small set of <strong>generic, deterministic, read-only tools</strong>: “look up a record by ID”, “list the recent runs for a source”, “show the delivery status of an item”. The tools run the queries. The model picks the tools, reads the results, removes the noise, and writes the answer.</p><p>The trick is keeping the tools generic. Not a hundred tools for a hundred questions, but about ten that answer most of them in combination. Fewer tools means a shorter prompt, better tool selection, and less code to keep correct.</p><h3>Part 2: The proof of concept</h3><p>The first version was a simple TypeScript API built on the Anthropic SDK. It answered questions by calling functions, and it chose those functions much like a good old rule-based classifier, except that the classifier was an LLM prompt.</p><ul><li>A <strong>stateless endpoint</strong> took a message and returned an answer.</li><li>A small <strong>intent classifier</strong> (a cheap pre-call to a fast model) narrowed the tools down to the relevant group before the main call.</li><li>Simple, single-domain questions went to <strong>Claude Haiku</strong>; ambiguous or multi-step ones went to <strong>Claude Opus</strong>. At today’s Bedrock list prices, Haiku 4.5 costs a fifth of Opus 4.5 per token, so every question routed to Haiku cost about a fifth of what Opus would have charged.</li><li>No budget, no agent loop, no retries and no observability.</li></ul><p>A test set of more than 500 real questions came back close to 80%<strong> right</strong> on the first run. Each answer was compared with a prepared expected answer and then reviewed by hand, with a check against the data wherever it quoted a number or a status. Good enough to know the idea worked. Not good enough to stop there.</p><p>The proof of concept also showed everything it couldn’t do:</p><ul><li><strong>No memory.</strong> Every question started cold. “And what about the next one?” meant nothing.</li><li><strong>Blocking I/O.</strong> Long model calls tied up the API’s request handling.</li><li><strong>A loop still to build.</strong> Retries, iteration limits and tool orchestration would be a few hundred lines that someone would have to write and maintain.</li><li><strong>No cost control.</strong> There was no way to cap spend, and tokens aren’t cheap, especially before the prompts are optimized.</li><li><strong>No limits.</strong> No rate limiting and no per-user cap, unless I wrote them.</li></ul><h3>Part 3: Moving to AgentCore</h3><p>That list is almost exactly what <strong>Amazon Bedrock AgentCore</strong> is built for: a managed <strong>Runtime</strong> that runs each session in its own microVM, a <strong>Gateway</strong> that serves your tools over MCP, <strong>Memory</strong> for conversations, and built-in <strong>Observability</strong> (<a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/">docs</a>).</p><p>There were two ways to use it:</p><ol><li><strong>Your own agent on AgentCore Runtime.</strong> You write the agent; AWS hosts it, isolates sessions and wires up memory and observability.</li><li><strong>The fully managed harness.</strong> AWS owns the loop entirely; you give it a prompt and tools.</li></ol><p>There’s no single right answer. If you want control over the loop, the prompts and the cost, and you’re happy to own that, the first option is the way to go. If your use case is small, your budget is comfortable and you prefer managed services, the second one is for you.</p><p>I went with the first, because it gave me more insight into the setup and more room to customize it. Cost was the clearest example. When I priced the managed harness, I couldn’t put the hard per-persona spend limits I wanted around it, and I’d have lost control over the prompts and the routing that kept costs low in the first place. (AgentCore has since added per-invocation iteration, timeout and token caps to the harness, so check the current docs before you decide.) With my own agent, I kept ownership of the prompt and the loop, and still got the managed surroundings.</p><h4>Why a Python agent</h4><p>The rest of your stack can be in any language: Java, TypeScript, Go or Rust. I’d still write the agent in Python, on purpose.</p><p>AgentCore Runtime accepts two kinds of artifact: a container image (any language, but then you own a Docker, registry and ARM image pipeline), or a <strong>zip of Python code uploaded to S3</strong>. Choosing the language was really choosing the packaging. Python gave me:</p><ul><li><strong>No new CI surface.</strong> The zip goes to S3 the same way Lambda bundles already do.</li><li><a href="https://strandsagents.com/"><strong>Strands Agents</strong></a> <strong>owns the loop.</strong> Retries and tool orchestration became about 80 lines of configuration instead of 300+ lines I’d have had to write and maintain.</li><li><strong>Near-free observability.</strong> The AWS OpenTelemetry distro plus Strands’ auto-instrumentation emits GenAI spans with no hand-rolled tracing.</li><li><strong>First-class memory hooks</strong> for AgentCore Memory.</li></ul><p>The trade-off is a small Python island in a codebase written in other languages. One rule contains it: the backend only depends on the agent’s <strong>response envelope</strong>, { answer, toolCallsExecuted, usage, hintsUsed } on success and { error: { reason, message } } on failure. If the agent is ever swapped for a container in another language, nothing on the backend changes.</p><p>Nothing was ripped out, either. The new stateful chat endpoint went live <strong>next to</strong> the old one-shot endpoint, and the rollback plan was to point callers back at the old one.</p><h4>What a turn looks like</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3jS155j2hEH-x1JiyK5wA.jpeg" /><figcaption>Generic agent platform architecture</figcaption></figure><p>The backend authenticates the user, resolves (or creates) the chat session and checks that the user owns it.</p><ol><li>It signs an InvokeAgentRuntime call to the runtime for that chat&#39;s persona.</li><li>The agent picks the hints that match the question, loads the conversation from Memory, and runs the loop: Bedrock picks tools, the Gateway runs them, the results go back to the model.</li><li>The agent writes the turn back to Memory and returns the envelope.</li></ol><p>With the platform settled, the real design questions turned out to be different ones. How do you add use cases without growing the context and the prompt? How do you expose different tools to different teams? How do you track cost per department? And how do you give each team its own configuration and security?</p><h3>Part 4: A second persona, and room for more</h3><p>The first assistant was built for one use case: sales. It talks about sales reports, this month’s revenue and new leads.</p><p>Then the inventory and engineering teams asked for the same thing, and they read data very differently, from different systems. Engineers want their ticket tracker, their log platform and their code host, all through MCP. The inventory team works with ERP integrations, spreadsheets and BI reports. An engineer wants the error log; a product specialist wants to know, in plain words, whether the customer will see the right thing. And each department’s reports should stay invisible to the others.</p><p>The quick fix was obvious: add a few tools to the existing agent and tweak the prompt. That was a trap.</p><ul><li><strong>One prompt with two jobs</strong> gets longer, more expensive and worse at both.</li><li><strong>One role that can reach two systems</strong> means keeping each persona away from the other’s tools depends on the code being right every single time.</li><li><strong>One budget</strong> means a spike from one group can take the assistant down for everyone.</li></ul><p>So a persona became <strong>configuration, not code</strong>. Every persona runs the same agent zip. What makes a persona different is:</p><ul><li>its <strong>system prompt</strong> file</li><li>its own <strong>Gateway</strong> with its own tools</li><li>its own <strong>IAM role</strong>, which can only call that one Gateway</li><li>its own <strong>Bedrock inference profile and budget</strong></li><li>its own <strong>hints file</strong>: what the team already knows, in small pieces (more on that in Part 8)</li><li>its own <strong>connections to the systems that team uses</strong>: MCP servers and APIs today, skills later</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rug5iCFVeqAjVZbOSVdrWA.png" /></figure><h4>How the Terraform is laid out</h4><p>Before the module call, here’s how the repo is organized. The split matters more than the files: what a persona owns, what decides which tools exist, and what wires the systems in.</p><pre>terraform/<br>├── modules/<br>│   ├── agentcore-persona/        # everything one persona owns<br>│   │   ├── main.tf               # inference profile, gateway, runtime<br>│   │   ├── iam.tf                # runtime role and gateway role<br>│   │   ├── budget.tf             # monthly budget, optional kill switch<br>│   │   ├── variables.tf<br>│   │   └── outputs.tf            # runtime_arn, gateway_id, gateway_url, ...<br>│   └── openapi-tool-filter/      # spec in, read-only spec out<br>│       ├── main.tf<br>│       ├── outputs.tf            # tool_spec_json, kept_operation_ids<br>│       └── filter.tftest.hcl<br>└── examples/<br>    └── four-personas/            # the wiring<br>        ├── shared.tf             # artifacts bucket, agent zip, Memory, hints files<br>        ├── main.tf               # module &quot;persona&quot;, once per persona<br>        ├── tools.tf              # gateway targets and credential providers<br>        ├── specs/                # OpenAPI specs of the target systems<br>        ├── allowed-tools.json    # the read-only allow-list per spec<br>        └── personas.tftest.hcl   # plan tests with a mocked AWS provider<br> <br>agent/src/persona_agent/prompts/  # one system prompt per persona, inside the zip<br>hints/                            # one hints file per persona, uploaded to S3</pre><p>Three rules keep it that way:</p><ul><li><strong>The persona module owns everything a persona has, and nothing else.</strong> It creates the inference profile, the gateway, the runtime, both IAM roles and the budget. It takes no gateway, no tools and no other persona as input. <em>Why:</em> isolation comes from what the module can’t be given, not from a review catching a wrong ARN.</li><li><strong>The filter module has no AWS resources at all.</strong> It’s a function: an OpenAPI spec and an allow-list go in, a smaller spec comes out. <em>Why:</em> the read-only rule can be tested offline in a few seconds, on every pull request.</li><li><strong>Only the example knows about real systems.</strong> Targets and credential providers live in tools.tf, outside the module, because they&#39;re different for every persona. <em>Why:</em> adding a system never touches the module, and adding a persona is one map entry, one prompt file and one hints file.</li></ul><p>That turns “add a persona” into a Terraform module call. Here’s the idea with four example personas, one per kind of team that might ask an assistant questions:</p><pre>locals {<br>  personas = {<br>    &quot;sales&quot;       = { prompt_file = &quot;sales.txt&quot;, monthly_budget = 40 }<br>    &quot;inventory&quot;   = { prompt_file = &quot;inventory.txt&quot;, monthly_budget = 40 }<br>    &quot;product&quot;     = { prompt_file = &quot;product.txt&quot;, monthly_budget = 100 }<br>    &quot;engineering&quot; = { prompt_file = &quot;engineering.txt&quot;, monthly_budget = 50 }<br>  }<br>}<br> <br>module &quot;persona&quot; {<br>  source   = &quot;../../modules/agentcore-persona&quot;<br>  for_each = local.personas<br> <br>  name                     = each.key<br>  prompt_file              = each.value.prompt_file<br>  model_monthly_budget_usd = each.value.monthly_budget<br>  budget_alert_emails      = var.budget_alert_emails<br> <br>  source_inference_profile_arn = var.source_inference_profile_arn<br>  foundation_model_arns        = var.foundation_model_arns<br> <br>  # Same code for every persona: one zip, every prompt file inside it.<br>  code_bucket      = aws_s3_bucket.artifacts.bucket<br>  code_package_key = aws_s3_object.agent_package.key<br> <br>  # Shared state: one Memory store for all personas.<br>  memory_id  = aws_bedrockagentcore_memory.chat.id<br>  memory_arn = aws_bedrockagentcore_memory.chat.arn<br> <br>  # Each persona reads only its own hints file.<br>  hints_s3_uri = &quot;s3://${aws_s3_bucket.artifacts.bucket}/${aws_s3_object.hints[each.key].key}&quot;<br> <br>  # Each gateway may use only the credentials and permissions of its own system (tools.tf).<br>  credential_provider_arns  = lookup(local.gateway_credential_providers, each.key, [])<br>  credential_secret_arns    = lookup(local.gateway_credential_secrets, each.key, [])<br>  gateway_policy_statements = lookup(local.gateway_policy_statements, each.key, [])<br>}</pre><p><em>Code:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/examples/four-personas/main.tf#L4-L40"><em>terraform/examples/four-personas/main.tf#L4-L40</em></a></p><p>One recommendation: <strong>bind each chat to one persona for its whole life.</strong> Save the persona when the chat is created, and let switching the toggle start a new chat. <em>Why:</em> Memory is keyed on (user, session), so if someone switched persona halfway through, the new agent would read a conversation full of tool calls it doesn&#39;t have.</p><h3>Part 5: Connecting to real systems</h3><p>The tools differ per persona, so they’re attached outside the module, one gateway target per system. None of them is a database. Each persona talks to the same APIs and MCP servers the rest of the company already uses, and those keep doing their own authentication and routing. The four systems below are the companion repo’s examples, set in a made-up games store; swap in your own:</p><ul><li><strong>Sales:</strong> system: Salesforce REST API; target type: OpenAPI, filtered to read operations; outbound auth: Salesforce OAuth</li><li><strong>Inventory:</strong> system: OpenSearch, the indices behind the BI dashboards; target type: OpenAPI, stored reports only; outbound auth: SigV4 with the gateway’s role</li><li><strong>Product:</strong> system: Legacy docs search API; target type: OpenAPI, filtered to read operations; outbound auth: API key from Secrets Manager</li><li><strong>Engineering:</strong> system: Company MCP servers (tickets, logs, code); target type: MCP server, one target each; outbound auth: OAuth client credentials</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iP-O2MD_eaY-gBXjxS1SHA.png" /></figure><p>The engineering target is the shortest of the four, because an MCP server already describes its own tools: one endpoint and one OAuth provider per server, and nothing else (<a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/examples/four-personas/tools.tf#L179-L201">tools.tf#L179-L201</a>).</p><p>Every target is optional. Leave a system’s variable out and that persona simply starts without tools for it. The repo’s plan tests check both cases: no targets until a system is configured, and each configured system on exactly one persona.</p><h4>Private systems, without opening them up</h4><p>The legacy docs API and the OpenSearch domain have no public endpoint, and AgentCore Gateway doesn’t run inside your VPC. So how does it reach them?</p><p>Through <strong>Amazon VPC Lattice</strong>. On the gateway target you set a private_endpoint with your VPC, subnets and security groups. AgentCore then creates a Lattice <strong>resource gateway</strong> in those subnets, with one network interface per subnet, and a <strong>resource configuration</strong> that points at exactly one endpoint: the API&#39;s or the domain&#39;s DNS name. Traffic from the gateway enters your VPC through those interfaces, and your security groups decide what it may reach. Nothing is exposed to the internet, and the gateway can&#39;t wander to anything else in the VPC.</p><p>Here’s the part of the inventory target that does it:</p><pre>  # SigV4 with the gateway&#39;s own role, so OpenSearch&#39;s access policy decides what it may read.<br>  credential_provider_configuration {<br>    gateway_iam_role {<br>      service = &quot;es&quot;<br>    }<br>  }<br> <br>  # The domain lives in a VPC: the gateway reaches it through VPC Lattice, not the internet.<br>  private_endpoint {<br>    managed_vpc_resource {<br>      vpc_identifier           = var.opensearch_bi.vpc_id<br>      subnet_ids               = var.opensearch_bi.subnet_ids<br>      security_group_ids       = var.opensearch_bi.security_group_ids<br>      endpoint_ip_address_type = &quot;IPV4&quot;<br>    }<br>  }</pre><p><em>Code:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/examples/four-personas/tools.tf#L106-L121"><em>terraform/examples/four-personas/tools.tf#L106-L121</em></a></p><p>If you’d rather own the Lattice resources yourself, for example to share them across accounts, there’s a self-managed mode: you create the resource gateway and resource configuration, and pass the configuration’s ID to the target instead.</p><p>One thing to check before you copy this: SigV4 from the gateway only works when the target service verifies the signature natively, and AWS documents a specific list of those services. If your OpenSearch domain isn’t covered, put a small API Gateway with IAM authorization in front of the search templates and sign for execute-api instead.</p><h3>Part 6: Security</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG0pI0OuXwRkq-8ncKHjoQ.jpeg" /></figure><p>Security isn’t a layer added at the end. Most of it is the shape of the system.</p><h4>The model never sees a credential</h4><p>Credentials never reach the agent. The Salesforce client secret and the docs API key sit in Secrets Manager, and the gateway fetches them through AgentCore Identity’s token vault at call time. Each gateway role can read only its own persona’s credentials. The model sees tool <em>results</em>, never tool <em>credentials</em>.</p><p>Just as important, the agent gets no shortcut around the systems you already trust. A few practical cases:</p><ul><li><strong>Salesforce still enforces Salesforce.</strong> The gateway calls the REST API as an integration user, so that user’s permissions and sharing rules apply to the agent exactly as they would to any other integration.</li><li><strong>The internal API keeps its own auth and routing.</strong> The legacy docs API checks the key, routes the request and applies its rate limits, the same way it does for every other client. Those are tested, deterministic code paths; the agent only chooses which one to call.</li><li><strong>Reports, not queries.</strong> The inventory persona can only run stored OpenSearch search templates, like stock_by_title or weekly_sell_through, and fill in their parameters. The query logic stays in the template, where someone reviewed it.</li><li><strong>MCP servers stay in charge of their tools.</strong> The company’s MCP servers authenticate the gateway with OAuth and decide for themselves what each tool may do.</li><li><strong>When a tool does need a database, the function owns it, not the model.</strong> Some questions have no API in front of them yet. Then the tool is a small Lambda behind its own gateway target. It sits in the VPC next to the database and fetches its database secret at runtime. Each tool runs one fixed, parameterized query, like <em>get the processing status of record X</em>. The model sends a record ID and gets rows back. It never sees the connection string, never writes SQL and has no network path to the database at all.</li></ul><h4>Least privilege, one role per box</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYHWB3MnElncKYCzZer3BA.png" /></figure><ul><li><strong>Backend API:</strong> can: Invoke the runtimes; cannot: Call Bedrock, the Gateways or any target system</li><li><strong>Persona runtime:</strong> can: Call Bedrock through its own profile, its own Gateway, Memory, its own hints file; cannot: Reach any target system, secret or credential directly</li><li><strong>Persona gateway:</strong> can: Use its own credential providers, and sign only its own SigV4 calls; cannot: Call Bedrock, Memory or another persona’s systems</li><li><strong>Target system:</strong> can: Apply its own authentication, authorization and rate limits; cannot: Be reached by anything but its persona’s gateway</li></ul><p>The persona module never takes a gateway as input. It creates its own and grants its runtime access to that one only, so it’s structurally impossible to wire one persona to another’s tools:</p><pre>statement {<br>    # This persona&#39;s own gateway only. The module takes no gateway as input,<br>    # so a persona can never be granted another persona&#39;s tools.<br>    sid       = &quot;CallToolGateway&quot;<br>    actions   = [&quot;bedrock-agentcore:InvokeGateway&quot;]<br>    resources = [aws_bedrockagentcore_gateway.gateway.gateway_arn]<br>  }</pre><p><em>Code:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/modules/agentcore-persona/iam.tf#L35-L41"><em>terraform/modules/agentcore-persona/iam.tf#L35-L41</em></a></p><h4>Read-only by default</h4><p>Every tool starts as a read. You can change that per persona (more on that below), but one thing never changes: the model gets no direct access to any data store. Read-only is enforced at two levels:</p><ol><li><strong>The model can’t see writes.</strong> Each OpenAPI spec is filtered down to an allow-list of operations before the gateway sees it, so createOrder, deleteDocument or a free-form SQL endpoint simply don&#39;t exist as tools.</li><li><strong>The credential can refuse writes too (optional).</strong> A token with only a read scope, or an integration user without write permissions, means even a leaked credential can’t change data. It’s a second lock, not a requirement.</li></ol><pre>locals {<br>  api_spec = jsondecode(var.openapi_spec_json)<br> <br>  tool_paths = {<br>    for route, item in local.api_spec.paths : route =&gt; {<br>      for method, op in item : method =&gt; op<br>      if contains(var.allowed_operation_ids, try(op.operationId, &quot;&quot;))<br>    }<br>    if length([<br>      for method, op in item : method<br>      if contains(var.allowed_operation_ids, try(op.operationId, &quot;&quot;))<br>    ]) &gt; 0<br>  }<br> <br>  tool_spec = merge(local.api_spec, { paths = local.tool_paths })<br> <br>  kept_operation_ids = flatten([<br>    for route, item in local.tool_paths : [for method, op in item : op.operationId]<br>  ])<br>}</pre><p><em>Code:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/modules/openapi-tool-filter/main.tf#L5-L24"><em>terraform/modules/openapi-tool-filter/main.tf#L5-L24</em></a></p><p>The repo tests this filter with terraform test, offline: PUT and DELETE on a path that also has a GET must disappear, an admin path with only writes must vanish entirely, and the inventory persona must end up with exactly one operation.</p><h4>Controlled write tools, when you need them</h4><p>Read-only is where I’d start, not where you have to stop. Say the sales team wants the assistant to submit an order. The same setup gives you several independent levers:</p><ol><li><strong>The spec.</strong> Add createOrder to the sales persona&#39;s allow-list, and only that one write operation becomes a tool.</li><li><strong>The credential.</strong> Give the Salesforce integration user permission to create orders, and nothing more.</li><li><strong>IAM.</strong> Only the backend role that serves the sales team may invoke the sales runtime, so the new tool is out of reach for everyone else.</li><li><strong>The conversation.</strong> Have the agent show the order and ask for a confirmation before it calls the tool.</li></ol><p>Each lever is separate, so you can open exactly one action for exactly one group, and close it again with a one-line change.</p><h4>The smaller things that matter</h4><ul><li><strong>Chat ownership.</strong> A chat is bound to the user who created it. Another user’s session ID gets a 403, never someone else’s history.</li><li><strong>Error hygiene.</strong> Raw AWS errors (which can contain ARNs and account IDs) are logged server-side; users get a generic, safe message.</li><li><strong>Data residency.</strong> Call Bedrock through a cross-region inference profile for your geography (EU, US or APAC, for example), so model traffic stays inside those regions, and keep Memory, hints and logs in the same region.</li><li><strong>Authentication on every hop.</strong> Here every call is SigV4-signed, from backend to runtime and from runtime to Gateway. That’s a choice, not a limit. The runtime and the gateway also accept OAuth (JWT) tokens from your own identity provider, such as Cognito, Okta or Entra ID, and gateway interceptors let you plug your own checks into every request and response.</li></ul><h3>Part 7: Scalability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xayx2J87SHpcaEsTBiEC6w.png" /></figure><p>The runtime gives you most of the scaling for free. Each chat session gets its own microVM, warm for that session and gone when it’s idle. There’s no always-on agent server to size, and nothing runs between conversations.</p><p>The interesting scaling problem isn’t traffic. It’s <strong>tools</strong>.</p><p>Every tool definition goes into the prompt on every turn. Add enough tools and you blow up the context, pay for it on every call, and the model gets worse at picking the right one. A gateway allows 1,000 tools, but a tool definition typically costs a few hundred tokens, so a couple of hundred tools already adds tens of thousands of tokens to every call. That’s why I keep my own ceiling far below the quota and scale <em>sideways</em>, not up:</p><ul><li><strong>Personas, then sub-personas.</strong> When a persona’s tool list gets long, it’s usually doing two jobs. Split it into another runtime and gateway; the module makes that cheap.</li><li><strong>One target per system.</strong> In the engineering persona, every company MCP server (tickets, logs, code) is its own target. A slow or broken server only affects its own tools, and each one can be added or removed on its own.</li><li><strong>Search, don’t list.</strong> Past a few dozen tools, turn on the gateway’s semantic tool search, so the agent looks tools up by intent instead of loading every definition on every turn.</li></ul><p>Adding a system is an OpenAPI spec (or an MCP endpoint), an allow-list entry and a terraform apply. The filtered spec is inlined into the target, so any change to the spec or the allow-list updates the target on the next apply, and CI runs the filter tests on every pull request.</p><h3>Part 8: Hints, not facts</h3><p>After a few weeks of real questions, a pattern showed up in the answers that went wrong. The model had the right tools. It just didn’t know what the team knew.</p><p>In the repo&#39;s games-store terms, a typical one looks like this. Someone asks how many digital keys are left for a new release. The assistant runs the stock report, adds up the numbers and answers with confidence. The tool worked, the maths was right, and the answer was still wrong: digital keys aren&#39;t stock, so the number meant nothing. Anyone on the inventory team would have said so in a second.</p><p>Engineers have the same kind of knowledge. Ask one why a record isn&#39;t live, and they don&#39;t read the record first. They check its processing status, then the last run for its source. None of that is in the database. It lives in people’s heads and in old Slack threads.</p><p>The obvious fix was to put all of it in the system prompt. That’s how a prompt grows three pages of edge cases, paid for on every turn and mostly irrelevant to the question in front of it.</p><p>So each persona gets a small file of <strong>hints</strong>: short learnings from earlier questions, each with a few keywords.</p><pre>{&quot;id&quot;: &quot;eng-01&quot;, &quot;keywords&quot;: [&quot;live&quot;, &quot;published&quot;, &quot;missing&quot;, &quot;stuck&quot;], &quot;hint&quot;: &quot;For &#39;why isn&#39;t X live&#39; questions, call get_processing_status first, then list_recent_runs for its source. It is faster than reading the record first.&quot;},</pre><p><em>Code:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/hints/engineering.json#L3"><em>hints/engineering.json#L3</em></a></p><p>On every turn, the agent picks up to three hints whose keywords match the question and adds them to that turn’s system prompt. Keyword matching sounds too simple. For tens of hints, it’s exactly enough, and the whole ranking is <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/agent/src/persona_agent/hints.py#L60-L68">nine lines of Python</a>.</p><p>A few rules keep hints from turning into a liability:</p><ul><li><strong>Hints, never facts.</strong> They arrive in a &lt;hints&gt; block that says they can be outdated, and every prompt says the same thing: use a hint to choose a tool or a word, never to state a fact. A tool result always wins.</li><li><strong>Attached, not deployed.</strong> Each file lives in S3 under a fixed key, and each persona’s role can read only its own file. <em>Why:</em> editing a hint reaches the next new chat without a new runtime version, so the people who know the domain can improve the assistant without a release.</li><li><strong>Fails open.</strong> A missing file or an S3 error means the agent answers without hints. A nice-to-have must never cost the user an answer.</li><li><strong>Out of the chat history.</strong> Hints go into the system prompt for one turn only, so Memory keeps what the user asked, not what the agent was nudged with.</li><li><strong>Measured.</strong> The response envelope carries hintsUsed. A hint that never shows up next to a good answer gets deleted.</li></ul><p>Past a few hundred hints, keyword matching won’t hold. That’s when I’d move to a vector search or a knowledge base. The handler only calls relevant(), so that&#39;s a swap, not a rewrite.</p><h3>Part 9: Budget</h3><p>One line dominates the bill: <strong>model inference</strong>. Runtime, Gateway, Memory and S3 together are rounding errors next to it. So the controls go in <em>before</em> the traffic, in two layers.</p><h4>Layer 1: a budget per persona</h4><p>Each persona calls Bedrock through its own <strong>application inference profile</strong>, a thin alias over the shared Claude profile that adds a cost-allocation tag. An AWS Budget filters on that tag. That gives every persona its own monthly cap and its own spend graph, and one persona’s spike can’t take another one down.</p><pre>resource &quot;aws_bedrock_inference_profile&quot; &quot;model&quot; {<br>  name        = &quot;${var.name}-model&quot;<br>  description = &quot;Model access for the ${var.name} persona&quot;<br> <br>  model_source {<br>    copy_from = var.source_inference_profile_arn<br>  }<br> <br>  tags = merge(local.tags, { CostCenter = var.name })<br>}</pre><p><em>Code:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/modules/agentcore-persona/main.tf#L16-L25"><em>terraform/modules/agentcore-persona/main.tf#L16-L25</em></a> <em>and the budget that filters on the tag:</em> <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/blob/0e960aa2ef28b371816d72009c01e24fe801fa9b/terraform/modules/agentcore-persona/budget.tf#L4-L27"><em>budget.tf#L4-L27</em></a></p><p>Two gotchas worth knowing. Invoking <em>through</em> a profile needs bedrock:InvokeModel on the profile <strong>and</strong> on every regional foundation model it fans out to; profile-only grants fail with AccessDeniedException. And the cost-allocation tag has to be activated once in Billing before the budget filter matches anything.</p><h4>Layer 2: an optional kill switch</h4><p>At 100% of a persona’s budget, an AWS Budgets action can attach a <strong>deny policy</strong> on bedrock:InvokeModel to that persona&#39;s runtime role. It&#39;s off by default, because it stops that persona completely until someone reverts it by hand. But it&#39;s one variable away when you need a hard ceiling.</p><h4>Why there’s no per-chat cap</h4><p>The first version had a third layer: a token counter per chat session in DynamoDB, which refused the next turn once a chat used up its cap. I took it out. It added a table, a write on every turn and one more thing that could fail in the middle of a conversation, to guard against a runaway chat that the persona budget already catches. What actually moved the bill was the size of every turn, not the length of a few chats, so the effort went into prompts and hints instead.</p><h4>What it actually costs</h4><p>AgentCore’s built-in tracing (you still pay normal CloudWatch ingestion) made the two numbers that matter, tokens and cost, visible from day one. They told a nice story:</p><ul><li>In the first month, about <strong>500 questions cost ~$50</strong>.</li><li>A few months later, about <strong>200 questions a month cost less than $5</strong>.</li></ul><p>Per question, that’s roughly a 5× drop: from around 10 cents to under 2. Nothing magic happened. Tighter prompts, less noise in tool results, and no context the model didn’t need. Watching cost per turn every week is what made those changes obvious.</p><h3>Part 10: What I’d do differently</h3><p>All three of these would have been cheaper to build per persona from day one than to add later.</p><p><strong>Start on AgentCore.</strong> The proof of concept taught a lot, but most of what it was missing (the loop, sessions, tracing, cost control) is exactly what AgentCore already has. Next time I’d prototype on the runtime from day one.</p><p><strong>Turn on long-term memory early,</strong> or at least capture the data for it. The hints files are a hand-written start, but the assistant still remembers a conversation, not a lesson. The sooner you record what each turn did and whether it helped, the sooner you can learn from it.</p><p><strong>Add a feedback signal immediately.</strong> Without a thumbs-up or thumbs-down, a wrong answer is silent. Accuracy you can’t measure is accuracy you can’t improve.</p><h3>Part 11: Where I want to take it</h3><p>Every idea below is another piece of per-persona configuration, not more agent code.</p><ul><li><strong>Long-term memory, as hints, never truth.</strong> Facts the agent learns per domain (aliases, known data quirks, which tools answered which question) would stop every chat starting cold. A live tool result always wins, any remembered status older than two weeks has to be re-checked, and memory namespaces include the persona from day one.</li><li><strong>A curated knowledge base, not a transcript dump.</strong> Distill recurring, <em>verified</em> answers into small knowledge cards, with a human approving every card. The hints files from Part 8 are the small, hand-written version of this today. Never feed raw transcripts back in, because that amplifies the confident-but-wrong answers.</li><li><strong>Agent skills instead of giant prompts.</strong> The engineering prompt has grown to cover ID formats, data quirks and output rules. Skills would load that knowledge only when it’s needed, and could run multi-step workflows with a human approving the action.</li><li><strong>A tool-gap report.</strong> The agent already signals which tools it wishes existed: every “tool not found”, every rephrase, every give-up. Clustering those into <em>proposed</em> tools, which an engineer then implements, turns usage into a roadmap. Never auto-generate executable tools.</li><li><strong>Continuous evaluations.</strong> The 500-question test set becomes a regression suite that runs against every prompt or tool change.</li><li><strong>Ticket integration.</strong> Answering the questions that used to become tickets is step one. Drafting the first reply on the ticket itself is step two.</li></ul><h3>If you’re about to build one</h3><ul><li><strong>Never let the model write queries.</strong> Give it a few generic, read-only tools and let deterministic code do the reading.</li><li><strong>Make a persona a deployment, not an </strong><strong>if statement.</strong> Its own prompt, gateway, role and budget. Isolation by IAM beats isolation by code review.</li><li><strong>Connect to systems, not databases.</strong> Let the agent call the APIs and MCP servers you already trust, with their authentication and routing intact.</li><li><strong>Start read-only, and open writes on purpose.</strong> Hide writes from the model by default, and when you need one, open exactly one operation for exactly one group.</li><li><strong>Put the cost controls in before the traffic.</strong> A budget per persona, and a kill switch you hope you never use.</li><li><strong>Give the model your team’s learnings as hints, not facts.</strong> Small, attached per persona, and checked against a tool every time.</li><li><strong>Keep the seam small.</strong> A stable response envelope means you can change the agent’s language, framework and hosting without touching the backend.</li><li><strong>Watch cost per turn every week.</strong> It’s the fastest way to find a bloated prompt.</li></ul><h3>What changed for the teams</h3><p>The questions still come. They just don’t land on an engineer first anymore. The questions that reached an engineer dropped by roughly four in five, and the feedback from the teams using it was good.</p><p>The bigger change was who improves it. The hints files belong to the domain owners now, not to engineering. They edit their team’s file, and a CI/CD pipeline syncs it to S3, so a better answer for the sales team ships without an engineer and without a release.</p><p>Adding a team changed too. A new persona now takes a few hours, not a project: add it to the Terraform personas map with its values, and set up authentication for the systems that team needs. Everything else comes from the module.</p><h3>Try it yourself</h3><p>The <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots">companion repo</a> has the persona module, the four-persona example, the Python agent, four example target systems and a hints file per persona, all set in a made-up games store. None of this needs an AWS account:</p><pre>pip install -r agent/requirements-dev.txt<br>make test      # 34 Python tests: handler, hints, envelope, prompts, SigV4<br>make tftest    # filter tests + a mocked-provider plan of all four personas</pre><p>make tftest is the one I&#39;d look at first. With mock_provider &quot;aws&quot;, Terraform plans the whole example offline, so the isolation rules are tested, not just described. The full results are in the appendix below.</p><p><em>How do you scope your agents: one big assistant, or one per audience? I’d like to hear what worked for you, especially if you went the other way. Issues and pull requests on the repo are welcome.</em></p><h3>Thank you</h3><p>This didn’t start as an architecture. It started as a Slack channel full of the same questions. The result is a system where one agent can wear many hats. The trick is making sure each hat fits exactly one head.</p><p>Thanks for reading this far. It’s a long one, and I’m grateful you gave it your time. If it saves you a few weeks of trial and error, send it to the engineer who answers your team’s support channel. They’ll know why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*wYMKQL_6TG2g5vxlpjhX7A.gif" /></figure><h3>Appendix: Test report</h3><p>Run on 22 November 2026 against commit <a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots/tree/0e960aa2ef28b371816d72009c01e24fe801fa9b">0e960aa</a>, fully offline: no AWS account, no credentials, no network calls to AWS.</p><ul><li><strong>Handler and envelope:</strong> Valid requests get the envelope; bad input is rejected before any model call; raw AWS errors never reach the user; a broken hint source never costs an answer</li><li><strong>Hints:</strong> Every persona has a valid hints file; keyword ranking; phrase keywords; duplicate IDs rejected; loading from S3; fails open; hints are labelled as not facts</li><li><strong>Prompts and config.</strong></li><li><strong>SigV4 signing:</strong> Calls from the agent to the gateway are signed</li><li><strong>OpenAPI filter:</strong> Only allow-listed operations survive; writes on shared paths and write-only paths are removed</li><li><strong>Four-persona plan</strong></li><li><strong>Formatting and schema.</strong></li></ul><p><strong>Total: 34 Python tests and 7 Terraform tests passed, 0 failed.</strong> Environment: Python 3.10.12, OpenTofu 1.13.9, AWS provider 6.x.</p><p>What these tests can’t cover: AgentCore Runtime, Gateway, Memory and Bedrock themselves. Everything that <em>decides</em> something (routing, filtering, hints, the envelope, persona wiring) is tested offline; the code that only wires AWS clients together isn’t.</p><h3>References and further reading</h3><p><strong>The companion code</strong></p><ul><li><a href="https://github.com/Chamindu36/agentcore-peronas-for-llm-chatbots">Companion repo: agentcore-personas</a>. Module, example, agent and offline tests.</li></ul><p><strong>AgentCore</strong></p><ul><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/">Amazon Bedrock AgentCore developer guide</a>. Runtime, Gateway, Memory, Identity and Observability.</li><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/bedrock-agentcore-limits.html">Amazon Bedrock AgentCore quotas</a>. Gateway, Runtime and Memory limits.</li><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-supported-targets.html">Supported targets for AgentCore Gateway</a>. Lambda, OpenAPI and MCP targets behind one MCP URL.</li><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-outbound-auth.html">Set up outbound authorization for your gateway</a>. OAuth, API key and SigV4 for gateway targets.</li><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-target-MCPservers.html">MCP servers as gateway targets</a>. Tool discovery and outbound auth for MCP targets.</li><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-interceptors.html">Using interceptors with Gateway</a>. Request and response Lambdas for custom validation and authorization.</li></ul><p><strong>Private connectivity</strong></p><ul><li>AWS docs, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-vpc-egress.html">VPC egress for gateway targets</a>. Private endpoints through VPC Lattice.</li><li>AWS Networking blog, <a href="https://aws.amazon.com/blogs/networking-and-content-delivery/private-connectivity-patterns-for-amazon-bedrock-agentcore-gateway-targets/">Private connectivity patterns for Amazon Bedrock AgentCore Gateway targets</a>. Managed and self-managed Lattice, side by side.</li><li>AWS Machine Learning blog, <a href="https://aws.amazon.com/blogs/machine-learning/configuring-amazon-bedrock-agentcore-gateway-for-secure-access-to-private-resources/">Configuring AgentCore Gateway for secure access to private resources</a>. Resource gateways and resource configurations, step by step.</li></ul><p><strong>Security, pricing and agent frameworks</strong></p><ul><li>AWS Machine Learning blog, <a href="https://aws.amazon.com/blogs/machine-learning/secure-ai-agents-with-policy-and-lambda-interceptors-in-amazon-bedrock-agentcore-gateway/">Secure AI agents with Policy and Lambda interceptors in AgentCore Gateway</a>. Deterministic policy plus dynamic checks on every tool call.</li><li><a href="https://aws.amazon.com/bedrock/pricing/">Amazon Bedrock pricing</a>. Per-token prices for Claude models.</li><li><a href="https://strandsagents.com/">Strands Agents</a>. The open-source agent loop used here.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ae59f1cf27d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Persistency & State Management: The Heartbeat of Architecture]]></title>
            <link>https://cudakara.medium.com/persistency-state-management-the-heartbeat-of-architecture-da3c3977f792?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/da3c3977f792</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 10:47:01 GMT</pubDate>
            <atom:updated>2025-06-24T10:47:01.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKc5fHToq1LhTOH31Gq0NA.png" /></figure><p>We often get caught up in architectural patterns, API gateways, queues, or microservice boundaries — but rarely pause to ask a more foundational question:</p><blockquote><em>“What must this system remember — and for how long?”</em></blockquote><p>In my view, that’s where the conversation about implementation architecture begins. Persistence isn’t just about where data sits. It’s the <strong>heartbeat</strong> of your system — the layer that outlives your codebase, infrastructure, and maybe even your product roadmap. Every time your app restarts or a container crashes, persistence determines whether users can continue their journey seamlessly or start from scratch. Most importantly, this part matters when things are not going our way (which is usually the case in a production system).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ruG6tECfqamLlP0-oiKyQ.png" /></figure><p>In this article, I want to unpack persistence and state management as <strong>first-class architectural concerns</strong>, not just database implementation details. It’s a mistake to treat this as a developer task to “<em>just store it in Mongo or Postgres.</em>” Because how and where we persist data defines:</p><ul><li>Whether the system feels reliable,</li><li>Whether the UI makes sense under failure,</li><li>And whether business continuity is possible at all.</li></ul><blockquote>💡 <strong>Analogy:</strong></blockquote><blockquote>Persistence in software is like memory in the human brain — it forms the continuity of experience. Without it, everything resets, and context is lost.</blockquote><h3>What Is Persistency in Software Architecture?</h3><p>At a high level, <strong>persistency</strong> refers to the ability of a system to retain data even after a process terminates or a service restarts[2]. But it goes much deeper than saving to disk. It’s about <strong>maintaining the integrity of meaningful state</strong> over time, across crashes, deployments, and API versions. Data outlives code. Data outlives infrastructure. Data is the system’s truth[1] according to Dr. Srinath Perera. And he’s right — your database is often the longest-living piece of a digital product. Therefore, designing for <strong>durable, consistent, accessible data</strong> is a responsibility every architect must take seriously.</p><p><strong>Let’s ground it in examples related to our property management system:</strong></p><p>At the surface level, it might look like:</p><ul><li>Keeping track of a form that a user submitted</li><li>Maintaining an active login session after a page refresh</li><li>Saving an invoice that’s waiting to be paid</li><li>Recording how much stock is left for a product</li></ul><p>But under the hood, to make that happen, you’re dealing with:</p><ul><li><strong>The <em>right storage medium</em> (SQL vs NoSQL vs cache)</strong></li><li><strong><em>Consistency strategies</em> in a distributed environment</strong></li><li><strong><em>Redundancy and failover plans</em> (so you don’t lose state during a crash)</strong></li><li><strong><em>Disaster Recovery mechanisms or replications</em></strong></li><li><strong>Handling <em>temporal and transitional states</em>, like a user in the middle of a multi-step process (e.g., onboarding or checkout)</strong></li></ul><p>Each of these aspects affects not just how the backend works, but how users perceive the product:</p><ul><li>Does the form they half-filled last night still open with saved values?</li><li>Will the payment retry automatically if it fails?</li><li>Can a support agent trace back all invoice versions?</li><li>Does the “out of stock” label actually match reality?</li></ul><p>Persistency isn’t just about storing bits or some data of a system. It’s about creating <strong>trust</strong> through memory. It’s about having a trustworthy source of truth for all aspects.</p><h3>💾 Storage Options: Choose Wisely</h3><p>One of the most foundational decisions we make as architects is where — and how — we store state. As software architects and engineers, we consistently face this challenge when designing new systems. It’s always a trade-off, and a definitive answer is rarely available, which is perfectly acceptable and expected. While it’s easy to default to “just use a database,” this is often where many architectural issues begin. The persistence layer you choose will define your consistency model, query capabilities, scalability limits, and even how intuitive your APIs feel to frontend engineers.</p><p>In my experience, selecting storage is less about technology preference and more about <strong>aligning data needs with system responsibilities</strong>. And in many modern architectures, you’ll likely use a combination of the following. And like I said, it’s always gonna be a tradeoff. Let’s briefly look into the different data storage options we use on a day-to-day basis for storing data and state.</p><h4>📊 SQL Databases (e.g., PostgreSQL, MySQL)</h4><p>Structured, relational, and battle-tested — SQL databases remain the default for transactional integrity and consistency.</p><p><strong><em>Best for:</em></strong></p><ul><li>Applications requiring strong ACID guarantees</li><li>Financial systems (payments, billing)</li><li>Admin interfaces and reporting dashboards</li><li>Systems with normalised schemas and clear relationships</li></ul><p><strong>Architectural Consideration:<br></strong><em>SQL works great when joins and referential integrity are essential. However, over-normalisation in microservices can sometimes backfire by coupling service boundaries to data schemas[1]. Always evaluate if a read-optimised copy or CQRS layer is needed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*hH-dV4z24HHZq19ttkp9YA.png" /><figcaption>SQL Databases. (Relational DBs)</figcaption></figure><h4>🤖 NoSQL Databases (e.g., MongoDB, DynamoDB, RedisJSON)</h4><p>NoSQL flips the model, offering schema flexibility, horizontal scalability, and developer speed.</p><p><strong>Best for:</strong></p><ul><li>Unstructured or semi-structured data</li><li>High-write workloads (e.g., logs, activity streams)</li><li>Denormalised document stores (e.g., product catalogues, profile snapshots)</li></ul><p><strong>Architectural Consideration:</strong></p><p><em>NoSQL doesn’t mean no design. Document stores like Mongo can become “junk drawers” without careful modelling[3]. Use JSON-based stores when domain aggregates naturally group together.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5IxGG_bykDMTUy9Y2PmUNQ.png" /><figcaption>No SQL Databases</figcaption></figure><h4>💡 In-Memory Stores (e.g., Redis, Memcached)</h4><p>If persistence is the brain, in-memory is its short-term memory. It’s ephemeral, volatile, and extremely fast[3].</p><p><strong>Best for:</strong></p><ul><li>Caching frequently accessed data</li><li>Session stores</li><li>Real-time leaderboard or counter updates</li></ul><p><strong>Architectural Consideration:</strong></p><p><em>Don’t rely on in-memory for long-term state. But when used properly (alongside persistent backing stores), it improves responsiveness significantly. Feature toggles, rate limiters, and token stores are great candidates.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNGXpQI8Qi9-gUOHHtuFZQ.png" /><figcaption>In Memroy Database options</figcaption></figure><h4>🗓 Event Logs (e.g., Kafka, Pulsar, EventStoreDB)</h4><p>Logs aren’t just for debugging — they’re a fundamental data storage model in event-driven architecture. Logs preserve all state transitions as immutable facts. And recently, these logs have become a part of compliance and security. Especially with the fintech domain, choosing the proper event logs storage is a massive decision for the success of the system.</p><p><strong>Best for:</strong></p><ul><li>Event sourcing systems</li><li>CQRS read model projections</li><li>Audit trails and compliance</li><li>Streaming and real-time analytics</li></ul><p><strong>Architectural Consideration:</strong></p><p><em>Event logs require a mental shift: you don’t store current state — you store changes. As Robert C. Martin says in Clean Architecture, “A history of events is often more valuable than the current state, because it can be replayed and analysed.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W138iRusl9SQWrq_FWSJrg.png" /><figcaption>Event logs database options</figcaption></figure><h4>🧱 Object Storage (e.g., Amazon S3 + Parquet, Azure Blob + Avro)</h4><p>Object stores aren’t just for static files anymore. They’ve evolved into highly durable, scalable data lakes — perfect for analytical, archival, and bulk storage use cases.</p><p><strong>Best for:</strong></p><ul><li>Storing large datasets (large statistical data logs, exports, backups)</li><li>Semi-structured data analytics (clickstreams, product feeds)</li><li>Data lake architectures</li><li>ETL/ELT pipelines that need to persist raw + transformed data</li></ul><p><strong>Architectural Consideration:</strong></p><p><em>While not optimised for point reads or transactional writes, S3 + Parquet (or Avro) provides:</em></p><ul><li><em>Cost-effective storage for massive volumes</em></li><li><em>Schema evolution via self-describing formats</em></li><li><em>Integration with query engines like </em><strong><em>Athena</em></strong><em>, </em><strong><em>Presto</em></strong><em>, </em><strong><em>Redshift Spectrum</em></strong><em>, or </em><strong><em>BigQuery</em></strong></li></ul><blockquote>👉 I often use this pattern in asynchronous data pipelines. For instance, product catalogues are first uploaded as Parquet files to S3 → then read by a transformer → finally synced to a NoSQL or search index. This creates a <strong>separation of durability, transformation, and delivery</strong>, which aligns well with event-driven architectures.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzQkB663_iv4Dzt5ifx9Ag.png" /></figure><blockquote><em>“Architecture is about trade-offs. Each choice gives you power but limits you elsewhere.”</em></blockquote><blockquote><em>— Mark Richards, </em>Fundamentals of Software Architecture[4]</blockquote><p>Choosing storage is not about picking the “best” tool — it’s about making intentional trade-offs that support how your system evolves, scales, and survives failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ndvSFrbSUUnvNyrVHHgsQ.png" /></figure><h3>⏳ Temporal State: Short-Term vs Long-Term</h3><p>In my view, one of the more subtle but critical aspects of architecture is recognising that <strong>not all data is meant to last forever</strong>.</p><p>Too often, we treat every piece of data as if it belongs in a permanent store, stuffing UI-specific state or intermediary workflow data into long-term databases. But that’s like taking notes on a napkin and then filing it in a corporate archive[2]. It bloats storage, complicates retrieval, and makes systems harder to reason about.</p><p>Instead, effective architectures <strong>respect the lifecycle of state</strong>, understanding whether it’s <strong>transient</strong> or <strong>durable</strong>, and placing it accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXaqIFofL6B9JW2VGkw8rA.png" /></figure><h4>🌀 Transient State: Short-Term and Ephemeral</h4><p>This is the data that <strong>lives briefly</strong> — for seconds, minutes, or maybe a session. It supports interactivity, user feedback, and task progression.</p><p><strong><em>🧾 Examples:<br>- </em></strong>Shopping cart contents before checkout<br>- Multi-step form data before submission (like tenant onboarding stages)<br>- Search filters or pagination settings<br>- Workflow progress indicators</p><p><strong><em>📦 Where it should live:</em></strong></p><ul><li><strong>Frontend memory</strong> (e.g. React state or Redux store)</li><li><strong>Session stores</strong> (Redis, browser localStorage)</li><li><strong>Workflow orchestrators</strong> (e.g. Step Functions, Temporal)</li></ul><p><strong><em>🔧 Architectural Tip: </em></strong><em>Avoid pushing this state into your primary database until it’s ready for persistence. For example, don’t store a partially completed onboarding form in PostgreSQL — use Redis or client-side storage instead.</em></p><h4>🏛 Durable State: Long-Term and Immutable or Auditable</h4><p>This is the <strong>source of truth</strong> — data that should survive restarts, outages, and even redesigns. It’s the “memory” of your system.</p><p><strong>🧾 Examples:<br>- </strong>Registered tenants and their metadata<br>- Finalised invoices and payment records<br>- Uploaded lease documents<br>- Past onboarding attempts and status logs</p><p><strong><em>📦 Where it should live:</em></strong></p><ul><li><strong>SQL/NoSQL databases</strong></li><li><strong>Object stores (S3, GCS) for documents and media</strong></li><li><strong>Event logs (Kafka/EventStoreDB) for auditable histories</strong></li></ul><p><strong><em>🔧 Architectural Tip: </em></strong><em>Design your APIs and services to </em><strong><em>commit transient state</em></strong><em> into durable state </em><strong><em>only at lifecycle boundaries</em></strong><em> — like checkout, form submission, or onboarding completion.</em></p><h3>💡 Real Example: Property Management Workflow</h3><p>Let’s say you’re building a tenant onboarding process:</p><ul><li>The tenant uploads ID, selects a payment plan, and signs a digital mandate.</li><li>While the form is half-filled, the state is stored in <strong>Redis</strong> (short-term).</li><li>Once the user completes all steps and hits submit, the backend writes this to <strong>PostgreSQL</strong> and logs the event in <strong>Kafka</strong> (long-term).</li></ul><p>This separation allows a better user experience (resuming from where they left off), improves fault tolerance, and avoids polluting your durable store with garbage or incomplete data.</p><h3>🔄 <strong>State Management &amp; Transactions: Building Confidence in Every Operation</strong></h3><p>As I’ve seen time and again in production systems, state management isn’t just about where data is stored — it’s about <strong>ensuring that state transitions are correct, complete, and recoverable</strong>. And that’s where the concept of <em>transactions</em> enters the picture.</p><h4>📌 <strong>What is a Transaction?</strong></h4><p>A transaction is a set of operations that must be completed as a single unit. It either <strong>fully succeeds</strong> or <strong>has no effect</strong>. This atomic behaviour is essential when multiple changes to the system state must occur together for consistency.</p><blockquote><em>“A system that updates the bank balance but fails to record the transaction history isn’t wrong because of storage — it’s wrong because of inconsistent state transitions.”</em></blockquote><blockquote><em>— </em>inspired by Clean Architecture, Robert C. Martin[3]</blockquote><h4>💼 Traditional ACID Transactions (e.g., SQL)</h4><p>In relational databases (like PostgreSQL or MySQL), we rely on <strong>ACID</strong> properties:</p><ul><li><strong>Atomicity</strong>: All or nothing</li><li><strong>Consistency</strong>: Valid state before and after</li><li><strong>Isolation</strong>: Transactions don’t interfere</li><li><strong>Durability</strong>: Once committed, it’s permanent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mj2-Y3PmXrOVW-Ozrz9_iQ.png" /><figcaption>ACID properties</figcaption></figure><blockquote>🧠 <strong>Real Example: Tenant Onboarding Step</strong></blockquote><blockquote>When a tenant confirms their onboarding: Create a tenant profile, Register a direct debit mandate, Generate an invoice and Log the audit trail</blockquote><p>In traditional ACID systems, this can be handled in a single transaction block. If any step fails, everything is rolled back.</p><pre>import { MongoClient } from &#39;mongodb&#39;;<br><br>const uri = process.env.MONGODB_URI || &#39;mongodb://localhost:27017&#39;;<br>const client = new MongoClient(uri);<br><br>interface TenantData {<br>  name: string;<br>  email: string;<br>  iban: string;<br>  amount: number;<br>}<br><br>export async function onboardTenant(data: TenantData) {<br>  const session = client.startSession();<br><br>  try {<br>    const db = client.db(&#39;rental_app&#39;);<br>    const tenants = db.collection(&#39;tenants&#39;);<br>    const mandates = db.collection(&#39;mandates&#39;);<br>    const invoices = db.collection(&#39;invoices&#39;);<br><br>    await session.withTransaction(async () =&gt; {<br>      // 1. Create tenant<br>      const tenantResult = await tenants.insertOne(<br>        { name: data.name, email: data.email },<br>        { session }<br>      );<br>      const tenantId = tenantResult.insertedId;<br><br>      // 2. Add mandate<br>      await mandates.insertOne(<br>        { tenantId, iban: data.iban, status: &#39;pending&#39; },<br>        { session }<br>      );<br><br>      // 3. Create invoice<br>      await invoices.insertOne(<br>        {<br>          tenantId,<br>          amount: data.amount,<br>          status: &#39;pending&#39;,<br>          createdAt: new Date(),<br>        },<br>        { session }<br>      );<br>    });<br><br>    console.log(&#39;✅ Transaction committed: Tenant onboarded&#39;);<br>  } catch (error) {<br>    console.error(&#39;❌ Transaction aborted:&#39;, error);<br>    throw error;<br>  } finally {<br>    await session.endSession();<br>  }<br>}</pre><p>But in <strong>distributed systems</strong>, ACID breaks down.</p><h3>🌐 State Management in Distributed Systems</h3><p>This is where architectural complexity truly begins to unfold. Unlike in a monolith, where state often lives in a single database or service layer, distributed systems spread state across boundaries — each microservice becomes the source of truth for a specific piece of data[1]. And while this division supports scalability and autonomy, it introduces a new class of challenges we must design around.</p><h4>🚧 The Big Challenges</h4><p><strong>1️⃣ Consistency Dilemmas (CAP Theorem)</strong></p><p><em>Distributed systems can’t have Consistency, Availability, and Partition Tolerance all at once. You must trade off:</em></p><ul><li><strong><em>Strong consistency</em></strong><em> → All clients see the same state at the same time</em></li><li><strong><em>Eventual consistency</em></strong><em> → State updates propagate asynchronously</em></li></ul><p><em>💡 Choose wisely depending on your user expectations and failure tolerance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOPWxumhruSn3K7qLnecDA.jpeg" /></figure><p>2️⃣ <strong>Idempotency</strong></p><p><em>In a world of retries and flaky networks, </em><strong><em>idempotent operations</em></strong><em> are non-negotiable.</em></p><pre>// Example: safely re-attempting onboarding step<br>POST /start-payment-onboarding<br>// This call should either:<br>// - create the mandate if it doesn&#39;t exist<br>// - return existing mandate if already created</pre><p><em>Making operations safe to retry allows services to recover without duplicating side effects — a core resilience pattern.</em></p><p>3️⃣ <strong>Service Coordination</strong></p><p><em>When a workflow spans multiple services (like onboarding, checkout, or order fulfilment), state needs to flow reliably.</em></p><ul><li><strong><em>Saga pattern</em></strong><em> for long-running, compensatable flows</em></li><li><strong><em>Choreography</em></strong><em> is services that emit and reacts to events</em></li><li><strong><em>Orchestration</em></strong><em> is a central controller that drives the workflow</em></li></ul><p>4️⃣ <strong>Partial Failures &amp; Retries</strong></p><p><em>Failures in distributed systems are partial, unpredictable, and often invisible. Good state management means knowing:</em></p><ul><li><em>What’s safe to retry</em></li><li><em>What failed and why</em></li><li><em>What has already succeeded</em></li></ul><p>🧠 Without this, systems become brittle, users lose progress, and bugs get buried under silent inconsistencies.</p><h4>🏢 Real-World Example: Tenant Onboarding (Property Management Platform)</h4><p>Let’s say we’re onboarding a tenant:</p><ul><li>🛂 <strong>Identity Service</strong> → status = Verified</li><li>🏦 <strong>Payment Service</strong> → status = Mandate Pending</li><li>🧩 <strong>Onboarding Aggregator</strong> → status = In Progress</li></ul><p>A well-designed system wouldn’t expose these fragmented pieces to the end user. Instead, it would <strong>surface a consolidated view</strong> like:</p><blockquote><strong>“Verifying payment setup… (3 of 5 steps complete)”</strong></blockquote><p>And underneath, services continue to update their states asynchronously, independent of one another. Whether we’re managing state inside a tightly scoped transaction or across loosely coupled services, the goal remains the same: building user trust by ensuring operations are reliable, traceable, and recoverable.</p><p>Transactions provide atomicity and certainty within service boundaries, while distributed state management requires patterns such as idempotency, coordination, and eventual consistency. [1] As architects and engineers, our job is to make complexity manageable, surfacing clarity from distributed state, ensuring progress even during partial failures, and enabling systems that recover gracefully without sacrificing user experience[2]. In my view, this is where technical excellence meets thoughtful architecture.</p><h3>CQRS &amp; Event Sourcing: When State Isn’t a Single Truth</h3><p>In most traditional systems, we treat the state as a single source of truth, usually a database row that reflects the latest status[4]. But in complex domains, that “truth” is often the product of many decisions, conditions, and workflows. This is where <strong>CQRS</strong> and <strong>Event Sourcing</strong> enter the conversation — not as default choices, but as precision tools for the right job.</p><h4>🧠 CQRS — Separate the Concerns</h4><p><strong>CQRS</strong> (Command Query Responsibility Segregation) splits your system into two distinct models:</p><ul><li><strong>Command side</strong>: Accepts write operations — changes that mutate state (e.g. POST /create-invoice, PATCH /update-user)</li><li><strong>Query side</strong>: Serves read models — optimised views tailored for consumers (e.g. /get-dashboard-metrics, /list-invoices-by-month)</li></ul><p>In my view, this separation brings clarity and flexibility, especially in systems where reads far outnumber writes or where read patterns evolve faster than business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*nz0LFW5bXRKTb7Pxa9tr3Q.png" /><figcaption>CQRS pattern</figcaption></figure><blockquote><strong>Example: In our property management system:</strong></blockquote><blockquote>- The command side updates the onboarding status (MarkTenantOnboarded)</blockquote><blockquote>- The query side serves user-friendly onboarding summaries (e.g. “3 of 5 steps completed”, “Bank mandate pending”)</blockquote><blockquote>This lets us project complex internal states into clean, stable UIs — without coupling them tightly to domain internals.</blockquote><h4>🔁 Event Sourcing — Store the Story, Not Just the Snapshot</h4><p>Where CQRS handles the separation of behaviour, <strong>Event Sourcing</strong> changes what we persist[6].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*NRyXz3r80471Or_fP49NLw.png" /><figcaption>Event Sourcing Pattern</figcaption></figure><blockquote><em>“You don’t store state. You store decisions.” — </em>Robert C. Martin, Clean Architecture</blockquote><p>Instead of updating and overwriting records, you store every <strong>event</strong> that changed the system, like:</p><ul><li><strong><em>TenantRegistered</em></strong></li><li><strong><em>MandateCreated</em></strong></li><li><strong><em>InvoiceIssued</em></strong></li></ul><p>The current state is then <strong>derived</strong> by replaying these events in order. This gives us:</p><ul><li><em>Full audit trails (what happened, when, and why)</em></li><li><em>The ability to </em><strong><em>rebuild the state</em></strong><em> from scratch if needed</em></li><li><em>Easy debugging and time-travelling through application logic</em></li></ul><blockquote><strong>Example: </strong>Suppose a tenant disputes an onboarding decision. With event sourcing, we can replay all state transitions to see exactly what happened — and when. That’s not just observability — it’s <em>accountability</em>.</blockquote><h4>✅ When to Use These Patterns</h4><p>Used together (or independently), <strong>CQRS</strong> and <strong>Event Sourcing</strong> are powerful — but they introduce <strong>operational complexity</strong>. We should reach for them when:</p><ul><li>Business workflows are long-running or require manual intervention</li><li>Auditability and traceability are essential (e.g. finance, legal)</li><li>Read scalability or flexibility is critical</li><li>You need to evolve the read models frequently without touching the core domain logic</li></ul><blockquote><strong>Architectural Tip</strong>: These patterns shine when paired with event-driven messaging (like Kafka or Pulsar) and append-only storage. But beware: debugging and onboarding new developers requires thoughtful documentation and observability support.</blockquote><h3>🗃️Persistence Patterns That Enhance Architecture</h3><p>By now, it should be clear that persistency isn’t just about <em>where</em> you store data — it’s also about <em>how</em> you move, transform, and recover it. Over the years, a few patterns have consistently emerged as game-changers, especially in distributed systems where failure is not just possible — it’s expected.</p><p>These aren’t just fancy tricks. They’re techniques build <strong>trust</strong> into your system.</p><h4>1️⃣ Outbox Pattern: Reliable Event Publishing</h4><p>In event-driven systems, there’s always the risk of inconsistency between your database and the events you emit[4]. What if your DB insert succeeds but the event doesn’t publish due to a crash?</p><p>The <strong>Outbox Pattern</strong> addresses this by storing the event <strong>inside the same transaction</strong> as your domain write. A background process then reads from this “outbox” table and safely publishes to your message broker (e.g., Kafka, SNS).</p><blockquote>🎯 Real Use: When a new tenant registers, the same transaction writes to the tenant table and the outbox. If the service crashes before sending to Kafka, the retry mechanism ensures eventual delivery.</blockquote><p>✅ This gives you <strong>atomicity</strong> across writes and events, reducing the risk of phantom records or missing events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*C7YkhkExlW3n14QzcBAI_A.png" /><figcaption>Outbox Pattern</figcaption></figure><h4>2️⃣ Write-Ahead Logging (WAL): Durability First</h4><p>Write-ahead logging ensures that <strong>all changes are first written to a durable log</strong> before applying them to the main data store. It’s used heavily in databases like PostgreSQL, Kafka, and even file systems.</p><p>Why? Because it’s the key to <strong>durability and crash recovery</strong>. If the system crashes mid-transaction, it can replay from the WAL and restore a consistent state.</p><blockquote>“Durability is not just about saving data. It’s about recovering your system’s brain after a blackout.”</blockquote><p>✅ Especially useful for systems that cannot afford to lose writes, even during power loss or node crashes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*y_rbpjOoezMzSRn5-2uk6A.png" /><figcaption>Write Ahead Logging Implementation</figcaption></figure><h4>3️⃣ Snapshotting: Efficient Event Sourcing</h4><p>Event sourcing lets you rebuild state from a full event history. But replaying 10,000+ events every time a user logs in? Not ideal.</p><p>That’s where <strong>snapshotting</strong> comes in: periodically, the system captures the current state and stores it. When rehydrating, you start from the last snapshot and only replay newer events.</p><blockquote>📦 Think of it like saving game progress. You don’t start from level 1 every time — you reload from your last checkpoint.</blockquote><p>✅ This significantly reduces load times and improves read model generation efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUQgdbRpuhF-8UTjwDn3iw.png" /><figcaption>Snapshotting in Event Sourcing</figcaption></figure><h4>4️⃣ Materialised Views: Fast Queries, Precomputed</h4><p>In read-heavy systems — especially when using CQRS — <strong>materialised views</strong> precompute complex queries into ready-to-serve formats.</p><p>Instead of hitting 5 tables to build a dashboard, your read model is already assembled in a flattened, query-optimised view[6].</p><blockquote>🔍 Real Use: A tenant’s payment summary can be precomputed and served via a single query (/tenant-dashboard) rather than joining payments, mandates, invoices, and rent entries.</blockquote><p>✅ Speeds up UI responses and reduces pressure on your core data models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*8qMqwo4S443hmVe2JN88vA.png" /><figcaption>Materialized View Implementation</figcaption></figure><p>These patterns ensure that your architecture doesn’t just work on good days — it survives bad ones too. So your system is maintainable and easy to recover from failures.</p><h3>🛟 Fallback Strategies for Persistency</h3><p>Even the most resilient systems are vulnerable to disruptions, be it a failed database write, a temporary network glitch, or a downstream service outage. The key isn’t to pretend these failures won’t happen[3]; it’s to <strong>design for them</strong> — to absorb them without breaking user trust or business workflows.</p><p>In my experience, <strong>the absence of fallback mechanisms around persistence is what causes the worst production outages and UX nightmares</strong>. That’s why resilient architectures go beyond retries — they anticipate partial failures and provide structured ways to <em>defer, recover, or compensate[1]</em>.</p><p>Here’s a breakdown of architectural strategies to make persistence failure-tolerant, recoverable, and user-safe:</p><h4>1️⃣ Graceful Degradation</h4><p>Rather than freezing workflows or returning 500s, fallback to <strong>degraded-but-usable modes</strong>:</p><ul><li>Show <strong>“Last Known Good”</strong> data from cache or replicas.</li><li>Allow users to continue tasks with a <strong>partial or placeholder state</strong>.</li><li>Mark operations as <strong>“Pending”</strong>, to be reconciled later.</li></ul><blockquote>✅ <strong>Example</strong>: If the invoice generation service fails during tenant onboarding, allow the user to proceed and flag the invoice step for later processing.</blockquote><h4>2️⃣ Redundant Persistence Paths</h4><p>Write to <strong>multiple sinks</strong> (e.g., S3, Kafka, backup DB) so data is never truly lost.</p><ul><li>Useful for audit logs, disaster recovery, and system replay.</li><li>Enables <strong>reconstruction of the critical state</strong> if your primary DB fails.</li></ul><blockquote>✅ <strong><em>Example</em></strong><em>: </em>Ingest events into Kafka and your transactional DB simultaneously. On failure, replay from Kafka to restore state.</blockquote><h4>3️⃣ Client-Side Retry Buffers</h4><p>Keep retryable operations <strong>temporarily on the client</strong>:</p><ul><li>Useful for offline scenarios or flaky mobile networks.</li><li>Leverage browser APIs (like IndexedDB or localStorage) to <strong>store pending mutations</strong>.</li></ul><blockquote><strong>✅ <em>Example</em></strong><em>: </em>A mobile app stores form submissions locally and auto-resubmits when the network reconnects — no user re-entry required.</blockquote><h4>4️⃣ . Fallback to Local Caches or Snapshots</h4><p>When live systems fail, serve <strong>stale-but-useful snapshots</strong> or <strong>cached results</strong>:</p><ul><li>Great for dashboards and analytics.</li><li>Enables <strong>read resilience</strong> without blocking the frontend.</li></ul><blockquote>✅<strong> <em>Example</em></strong><em>: </em>If a dashboard backend times out, show the last synced snapshot from Redis with a banner: “Data as of 10:42 AM.”</blockquote><h4>5️⃣ Queue-Based Write Deferral</h4><p>When your DB is down, don’t drop writes — <strong>defer them via queues</strong>:</p><ul><li>Use Kafka, RabbitMQ, or SQS to <strong>persist the user’s intent</strong>.</li><li>A consumer retries the write asynchronously until success.</li></ul><blockquote>✅ <strong><em>Example</em></strong><em>: </em>If your transaction service fails, enqueue the payment record. Once the DB recovers, replay and persist.</blockquote><h4>6️⃣ Compensating Transactions (Saga Pattern)</h4><p>In distributed systems, <strong>undoing a partial workflow</strong> is often safer than trying to force a rollback.</p><blockquote>✅ <strong><em>Example</em></strong><em>: </em>If a tenant onboarding flow fails after invoice generation, issue compensating actions: cancel the invoice, revoke the mandate, and mark onboarding as incomplete.</blockquote><p>This forms the backbone of <strong>Saga-based workflows</strong>, especially in financial or multi-step processes.</p><h4>7️⃣ Deferred Writes with Durable Queues</h4><p>Capture failed writes as <strong>commands/events</strong>, and let a <strong>resilient processor</strong> persist them when safe.</p><blockquote>✅ <strong><em>Example</em></strong><em>: </em>Log user actions to an outbox table or Kafka topic. A background worker retries the writes using <strong>exponential backoff</strong>, ensuring the write eventually succeeds.</blockquote><h4>8️⃣ Dual Writes with Delayed Commit Logic</h4><p>When the final state depends on validation or multi-service checks:</p><ol><li>Save a <strong>provisional write</strong> to a buffer.</li><li>A background service evaluates rules.</li><li>Promote to the <strong>main DB</strong> once valid.</li></ol><blockquote><strong>✅ <em>Example:</em></strong><em> </em>User changes address → saved to staging table → fraud check runs → update confirmed.</blockquote><h4>9️⃣ Scheduled Compensation Policies</h4><p>Sometimes, fallback isn’t real-time — it’s <strong>scheduled recovery</strong>:</p><ul><li>Use background jobs to reconcile the inconsistent state.</li><li>Queue unresolved records for <strong>manual or automated compensation</strong>.</li></ul><blockquote>✅<strong> <em>Example</em></strong><em>: </em>If invoice generation fails after 3 retries, flag it for back-office review the next day.</blockquote><p>Fallbacks are not Band-Aids — they’re <strong>intentional architectural guarantees</strong>. These patterns recognise that persistence isn’t always about perfect writes; it’s about <strong>capturing user intent reliably</strong>, even under failure.</p><blockquote><em>“You don’t store state. You store decisions.”</em></blockquote><blockquote><em>— </em>Robert C. Martin, Clean Architecture[2]</blockquote><p>Whether it’s queues, retries, compensations, or caches, a <strong>fallback-aware architecture separates resilient systems from brittle ones</strong>.</p><h3>🧠 Wrapping Up: Persistency as the Backbone of Reliable Systems</h3><p>Persistency and state management are not just about data — they are about continuity, trust, and the ability to recover from the unexpected. From choosing the right storage engine to handling distributed consistency and designing for fallback, each architectural decision reinforces how dependable your system feels in the eyes of the user and the business.</p><p>In my view, getting persistency right means treating state as a first-class citizen in your design process, not a backend afterthought. <strong>It means thinking not just about <em>where</em> we store, but <em>how</em>, <em>why</em>, and <em>what happens when it fails</em></strong>. Because systems that handle failure gracefully are the ones that earn long-term trust from users, developers, and stakeholders alike.</p><p><strong>🔐 What’s Next: Security as a System Concern, Not a Checkbox</strong></p><p>In the next article, I’ll shift focus to <strong>Security concerns</strong>, not as a compliance requirement or an OWASP checklist, but as an architectural discipline. We’ll explore how thoughtful system design can help enforce trust, protect data, and shape safe user experiences — right from the drawing board.</p><p>Stay tuned. 🧩🔒</p><h3>📚 References</h3><ol><li>Srinath Perera, <em>Software Architecture and Decision-Making: Leveraging Leadership, Technology, and Product Management to Build Great Products</em>, 2023.</li><li>Robert C. Martin, <em>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</em>, Prentice Hall, 2017.</li><li>Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship, Prentice Hall, 2008.</li><li>Mark Richards and Neal Ford, <em>Fundamentals of software architecture: an engineering approach, 2020</em></li><li><a href="https://bytebytego.com/guides/what-does-acid-mean/">https://bytebytego.com/guides/what-does-acid-mean/</a></li><li><a href="https://medium.com/design-microservices-architecture-with-patterns/event-sourcing-pattern-in-microservices-architectures-e72bf0fc9274">https://medium.com/design-microservices-architecture-with-patterns/event-sourcing-pattern-in-microservices-architectures-e72bf0fc9274</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da3c3977f792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Architecture Meets UX: Designing Software for Humans, Not Just Machines]]></title>
            <link>https://medium.com/design-bootcamp/architecture-meets-ux-designing-software-for-humans-not-just-machines-a58a42550711?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/a58a42550711</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-architect]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 22:07:28 GMT</pubDate>
            <atom:updated>2025-06-25T00:13:30.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w23vVTUvD2W5RoXNGEiiMQ.png" /></figure><h3>🧩 Introduction: The Human Side of Architecture</h3><p>In the previous articles of this series, we explored the mechanics of architecture — from utilising mental models to make informed decisions to structuring code and components, optimising system performance, and ultimately, handling communication and coordination across distributed systems. Each of those choices focused on how <strong>the system works internally</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2q3YOnN_RZWzhSpANyIrQ.jpeg" /></figure><p>But there’s a layer even more important than internal correctness:</p><h4><strong><em>How humans experience the system we’ve built.</em></strong></h4><p>This is where <strong>User Experience (UX)</strong> comes in — not as a separate concern handed off to designers, but as a natural extension of architecture itself. Every architectural decision we make — whether it’s API design, service boundaries, data contracts, or coordination models — eventually shows up in the way users perceive <strong>speed, clarity, trust, and flow</strong> in the product[2].</p><p>In this article, I want to explore <strong>how architecture directly shapes UX</strong> and why architects (not just designers) must care deeply about how users experience our systems.</p><h3>🔎 The Role of Architecture in UX</h3><p>When I think about architecture’s impact on UX, I often refer back to a simple but powerful framing presented in <em>Software Architecture and Decision-Making[1]</em>:</p><blockquote><em>“Architecture is fundamentally about managing uncertainty and reducing risks.”</em></blockquote><p>UX failures are one of the highest risks in software. A system that scales beautifully but confuses its users still fails. A perfectly decoupled service mesh that leads to unpredictable user flows still fails. Then again UX is not about having nice and vibrant user interfaces or mobile applications. Architectural decisions ripple directly into UX outcomes through multiple dimensions:</p><h4>2.1 ⚡ System Responsiveness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*YlEjoNBvpl_57OnGz9c1lw.avif" /></figure><p>The responsiveness of the system isn’t only about server performance — it’s how quickly <strong>users feel that their actions have an effect</strong>.</p><blockquote><strong>Eg: </strong>When a tenant submits their rental application, several services must be executed:<br>- Identity verification<br>- Direct debit mandate setup<br>- Contract generation<br>- Invoice pre-generation</blockquote><p>If the architecture forces these to happen serially, the UI feels sluggish. But by designing the backend to perform <strong>parallel calls</strong> where possible, and allowing <strong>partial progress updates</strong>, the system feels much faster even if total processing time remains the same. The architecture determines not just system throughput but perceived responsiveness[4].</p><h4>2.2 🔄 Consistency &amp; Predictability</h4><p>A good UX keeps users confident about where they are and what’s happening. Architecturally, this depends on how state transitions are managed across distributed services.</p><blockquote><strong>Eg:</strong> When a tenant signs up for direct debit, their onboarding status moves through multiple backend services.</blockquote><p>If some services are <strong>eventually consistent</strong> but the UI doesn’t reflect this properly <em>(</em><strong><em>Eg:</em></strong><em> showing “Payment Setup Complete” while the bank mandate is still pending)</em>, users get confused.</p><p>The good architecture supports UX hereby:</p><ul><li>Publishing <strong>clear, consolidated status events</strong>.</li><li>Having the UI reflect the system state accurately, even if asynchronously.</li><li>Avoid exposing internal service dependencies to the end user[3].</li></ul><h4>2.3 🔄 Recoverability &amp; Error Tolerance</h4><p>UX often comes into play when we provide maintenance and support to the system. We can omit UX decisions during the initial research and development process. Therefore, UX is also about <strong>what happens when things fail</strong>.</p><blockquote><strong>Eg:</strong> If a payment attempt fails because of a temporary bank API issue, can the user retry? Is the error message actionable? Can the system recover without requiring full re-onboarding?</blockquote><p>This is where <strong>graceful degradation</strong>, retries, and state-based recovery workflows (designed at the architectural level) directly support smoother UX. In a nutshell, the less the user sees your internal failures, the better your architecture is.</p><h4>2.4 🎯 Workflow Alignment to Real User Goals</h4><p>One of the biggest UX problems stems from systems being designed around technical domains rather than user journeys. Architecture should align services and APIs to <strong>real-world tasks</strong> users are trying to complete.</p><blockquote><strong>Eg:</strong> Instead of having the UI orchestrate separate flows like:<br>- “Upload ID Document”<br>- “Request Bank Mandate”<br>- “Generate First Invoice”</blockquote><blockquote>We design backend APIs that expose higher-level <strong>business workflows</strong>:<br>- <strong>POST </strong>/onboard-tenant<br>- <strong>GET </strong>/onboarding-status</blockquote><p>This reduces client-side complexity, improves UX consistency, and abstracts away cross-service coordination — <strong>moving coordination into architecture, not UI logic. </strong>UX flows should reflect user intent, not backend wiring[3]<strong>.</strong></p><h3>🖥 UI as a System Integration Layer</h3><p>In modern distributed systems, especially microservices, the UI is no longer just a screen renderer — and I learned this the hard way. In my early days, I used to think UI and UX were basically the same thing. But I was completely wrong. UX goes far beyond just the visual interface — it even plays a major role in <strong>integration and coordination[1]</strong>.</p><p>The UI often behaves like a mini-orchestrator: managing state, coordinating backend services, dealing with eventual consistency, and gracefully handling partial failures[4]. In other words: <strong><em>The user interface becomes part of the system’s runtime coordination layer.</em></strong></p><h4>🔍 Real Example: Tenant Onboarding Flow</h4><p>Let’s revisit our property management system. When a tenant begins onboarding, the UI must:</p><p>1️⃣ Collect personal details and documents (while aligning to GDPR)<br>2️⃣ Trigger identity verification service<br>3️⃣ Initiate direct debit mandate with external payment providers<br>4️⃣ Request document signing<br>5️⃣ Prepare initial invoice estimate</p><p>Behind these simple steps, 5+ microservices may interact asynchronously. But from the tenant’s perspective, they just see a single onboarding screen with a progress indicator. The frontend UI stitches together:</p><ul><li>Parallel backend calls where possible</li><li>Eventual consistency states (e.g. waiting for mandate confirmation)</li><li>Polling or subscription to event streams</li><li>Local state management for responsiveness</li></ul><p>The UI increasingly needs strong support from the architecture:</p><ul><li>Clear service contracts</li><li>Idempotent APIs (safe to retry failed operations)</li><li>Status endpoints (/onboarding-status) instead of raw entity reads</li><li>Backend coordination patterns that support staged UI updates</li></ul><p>By thinking of the UI as part of system integration, we prevent brittle client-side workflows and achieve smoother UX even in complex distributed systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsFRCnkTXDYAljS7xtSgcQ.png" /><figcaption>UI and UX</figcaption></figure><h3>🧠 Cognitive Load &amp; Mental Models</h3><p>Ultimately, <strong>UX is about managing user cognition</strong>. When I say <strong>UX is about managing user cognition</strong>, we mean that:</p><ul><li>Users don’t interact with the system based on how it’s architected.</li><li>Users interact with the system based on how their brain expects things to work (Intuition).</li><li>Good UX aligns the system’s behaviour with the way humans naturally think, process, and act.</li></ul><p>Users don’t care how services are split or what your deployment topology looks like — something we developers are very well aware of. They simply want to complete their tasks intuitively, without being forced to understand the system’s internal workings.</p><h4>🔍 Real Example: Payment Status</h4><p>In our property management system:</p><ul><li>Internally, the system may track payment authorization, bank mandate confirmation, and invoice status across multiple databases and services.</li><li>But the UI simplifies this complexity into a single high-level message:</li><li><em>“Direct Debit Setup: In Progress / Completed / Failed”</em></li></ul><p>This is the UX version of <strong>abstraction boundaries</strong> we apply in clean architecture:</p><ul><li>Expose meaningful state, not raw data</li><li>Hide unnecessary intermediate steps</li><li>Present workflows that match user mental models</li></ul><h3>🔥 Error Handling as UX</h3><p>One of the most overlooked aspects of UX is how the system behaves under <strong>partial failures (the worst type of failures)</strong> — those moments when <em>some</em> parts of the system work while others temporarily fail. These are not full outages, but intermittent issues: <em>timeouts, slow responses, flaky external services, or network hiccups.</em></p><p>👉 And this is where <strong>architecture quietly makes or breaks the user experience</strong>.</p><p>Most users will forgive minor delays or retries — but they won’t forgive losing data, getting confusing errors, or having to start over. That’s why failure handling isn’t just a backend concern — it’s a <strong>first-class UX issue[4</strong> that architects must design for intentionally.</p><h4>🔍 Real Example: Payment API Timeout</h4><p>When a tenant sets up a direct debit, the system calls out to the external payment provider to verify and register the bank mandate. But what if:</p><ul><li>The provider’s API is temporarily unavailable?</li><li>Is the network call times out?</li><li>The bank’s system is under maintenance?</li></ul><p><strong>👉 Now, you have two choices:</strong></p><p>❌ <strong>The bad UX way:</strong></p><blockquote>The front end freezes, shows a generic error (“Something went wrong”), and forces the user to refresh and start over.</blockquote><p>✅ <strong>The good UX way (Architected properly):</strong></p><blockquote>- Persist the payment request as <strong>“Pending”</strong> in your backend.<br>- Use <strong>background retries</strong> (with exponential backoff) to automatically reattempt the operation.<br>- If retries eventually fail, notify the user proactively (“We couldn’t verify your payment — please update your mandate.”).</blockquote><h4>🧠 Architectural Patterns that Improve Failure UX:</h4><h4><strong>1. Saga Patterns</strong>:</h4><p>In a distributed system, you often have workflows that span multiple services where <strong>either everything should succeed, or the system should clean up safely if something fails mid-way</strong>. Since you can’t use database transactions across services, Sagas handle coordination through a sequence of steps and compensating actions. Sagas ensure the workflow is either fully complete or compensates automatically — keeping the user experience consistent[4].<br><strong>Example: <em>Tenant Onboarding</em></strong></p><ul><li><em>Step 1: Register tenant profile ✅</em></li><li><em>Step 2: Initiate direct debit mandate ✅</em></li><li><em>Step 3: Generate first invoice ✅</em></li><li><em>Step 4: Send welcome email ❌ (email service temporarily unavailable)</em></li></ul><p><em>👉 Instead of leaving the system in an inconsistent state, the Saga rolls back or schedules compensating actions:</em></p><ul><li><em>Cancel the invoice generation</em></li><li><em>Mark the mandate as unconfirmed</em></li><li><em>Notify admins for manual follow-up</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXJmiGDAdefGfTKPeIl8wQ.png" /></figure><h4><strong>2. Retry queues</strong>:</h4><p>Not every failure requires full rollback. Often failures are temporary — for example, a network glitch or a temporary 503 from an external API. Retry queues automatically reprocess these failed operations <strong>without user intervention</strong>.</p><p><strong>Example: <em>Payment API Timeout</em></strong></p><ul><li><em>The payment provider API fails to respond on the first attempt.</em></li><li><em>The system persists the request in a retry queue.</em></li><li><em>Retries are automatically scheduled with exponential backoff (e.g. retry after 1 min, then 5 min, then 15 min).</em></li><li><em>Most transient failures succeed on retry, and the user doesn’t experience any disruption.</em></li></ul><p>👉 The user simply sees:<br><em> “We’re verifying your payment setup. This may take a few minutes.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nL_ivdKuh2RU_a6eXoIr-w.png" /></figure><h4><strong>3. Fallback APIs:</strong></h4><p>When a service is unavailable, fallback APIs provide <strong>limited functionality</strong> that keeps the system usable while waiting for full recovery.</p><p><strong>Example: <em>Invoicing System</em></strong></p><ul><li><em>The tax calculation service is down.</em></li><li><em>Instead of fully blocking invoice generation, fallback logic produces a </em><strong><em>provisional invoice</em></strong><em> without tax breakdown.</em></li><li><em>The user sees:<br></em><strong><em>“Invoice generated — tax calculation pending.”</em></strong></li></ul><p><em>👉 The system continues to function while gracefully signalling partial results.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqtCh8d3u1EQpjIqcy9UmQ.png" /></figure><h4><strong>4. Compensating actions:</strong></h4><p>When a downstream failure occurs after some work has already been completed, compensating actions safely undo those changes — preventing data inconsistencies.</p><p><strong>Example: <em>Direct Debit Onboarding</em></strong></p><ul><li><em>Mandate registration succeeds ✅</em></li><li><em>Initial invoice is generated ✅</em></li><li><em>Bank rejects mandate at final verification ❌</em></li></ul><p><strong><em>👉 The system triggers compensating actions:</em></strong></p><ul><li><em>Cancel the generated invoice.</em></li><li><em>Remove the mandate record.</em></li><li><em>Reset tenant onboarding status.</em></li><li><strong><em>Inform the tenant politely:</em><br></strong><em>“We couldn’t verify your bank details. Please update your payment method.”</em></li></ul><p>Good error handling makes failure <strong>invisible or manageable</strong>, not terrifying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95iRrBoMIHXLUr3lIKJ2aQ.png" /></figure><h3>8️⃣ 🧑‍🤝‍🧑 Conway’s Law Applies to UX</h3><p>Conway’s Law states:</p><blockquote><em>“The system architecture mirrors the communication structure of the organization.”</em></blockquote><p>When team structures are disconnected, this often creates UX fragmentation.</p><h4>🔍 Example: Team Misalignment</h4><blockquote>The onboarding team owns tenant data<br>The payment team owns a direct debit<br>The invoicing team owns billing estimates</blockquote><blockquote>If these teams don’t collaborate, the tenant onboarding screen ends up being a patchwork of disjointed API calls, with inconsistent error handling and unclear state transitions.</blockquote><h3>🎨 UX Concepts Every Architect Should Know</h3><p>As architects and software engineers, we often focus deeply on system design, scalability, and performance — after all, that’s where most of our training and daily work happens. But systems aren’t built for servers; they’re built for people. No matter how elegant our service boundaries, database schemas, or deployment pipelines are, <strong>our users experience only what we expose to them through UX (</strong>in my personal opinion, achieving that is often easier said than done)<strong>.</strong></p><p>That’s why, as architects or SEs, we need to intentionally consider a set of <strong>foundational UX principles[1]</strong> that directly influence how users perceive reliability, simplicity, and trust in the system.</p><ol><li><strong><em>Emotional Response — How your system “feels” to users</em></strong></li><li><strong><em>Efficiency — Minimizing user effort</em></strong></li><li><strong><em>User Psychology — Matching system behaviour to user expectations</em></strong></li><li><strong><em>Feedback &amp; Iteration — Designing for continuous learning</em></strong></li><li><strong><em>Visual Design, Interactivity &amp; Layout — The part users see</em></strong></li></ol><p>These concepts help us bridge the gap between technical correctness and real-world usability — ensuring that the systems we build don’t just function correctly, but actually serve people intuitively[3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWXSQrERKUuMeViejzGtSg.png" /></figure><h4>1️⃣ Emotional Response — How your system “feels” to users</h4><p>UX isn’t only about whether the system works — it’s about how users feel while using it.</p><ul><li>Are they frustrated waiting for responses?</li><li>Are they confused by unexpected states?</li><li>Do they trust your system to work reliably?</li></ul><p><strong>Example :</strong></p><p><em>When tenants onboard, showing real-time progress (“Verifying ID… Bank Mandate Processing… Invoicing Setup Complete”) reduces anxiety and builds trust — even if actual backend processing takes several minutes.</em></p><p><em>✅ </em><strong><em>Architectural Implication:</em></strong></p><p><em>Expose backend progress as clear status transitions via APIs, not vague “loading” spinners.</em></p><h4>2️⃣ Efficiency — Minimizing user effort</h4><p>Good UX enables users to complete tasks quickly and easily.</p><ul><li>Reduce redundant steps</li><li>Pre-fill known information</li><li>Provide meaningful defaults</li></ul><p><strong>Example:</strong></p><p><em>When setting up direct debit, if tenant information is already known from onboarding, pre-fill payment forms instead of forcing re-entry.</em></p><p><em>✅ </em><strong><em>Architectural Implication:</em></strong></p><p><em>Design APIs that aggregate data needed for the UI (/get-tenant-onboarding-data) rather than forcing multiple round-trips across microservices.</em></p><h4>3️⃣ User Psychology — Matching system behaviour to user expectations</h4><p>Users approach your system with mental models. The better your system aligns with these, the more intuitive it feels.</p><ul><li>Use consistent terminology</li><li>Avoid exposing internal technical states</li><li>Predictable outcomes for similar actions</li></ul><p><strong>Example:</strong></p><p><em>The tenant thinks in terms of “Upcoming Rent” not “Generated Invoice Documents”. Expose “Next Payment Due: €500 on August 1” — not invoice IDs, ledger entries, or payment batches.</em></p><p><em>✅ </em><strong><em>Architectural Implication:</em></strong></p><p><em>Build </em><strong><em>user-centric abstractions</em></strong><em> into service boundaries, even if internally the data flows are complex.</em></p><h4>4️⃣ Feedback &amp; Iteration — Designing for continuous learning</h4><p>UX is not one-and-done. Real users will always surprise us. Your architecture must allow for safe, iterative evolution:</p><ul><li>Versioned APIs to introduce improvements gradually</li><li>Feature toggles for controlled rollouts</li><li>Capturing user behaviour analytics to inform changes</li></ul><p><strong>Example :</strong></p><p><em>If many tenants drop off during payment setup, A/B tests simplified flows and analyzes event data to improve onboarding.</em></p><p><em>✅ </em><strong><em>Architectural Implication:</em></strong></p><p><em>Support metrics, telemetry, feature flags, and backwards-compatible changes at the architectural level.</em></p><h4>5️⃣ Visual Design, Interactivity &amp; Layout — The part users see</h4><p>While these are heavily UI-focused, architects still influence:</p><ul><li>How much data is fetched and displayed</li><li>The pacing of interactivity (blocking vs async flows)</li><li>Responsiveness across devices</li></ul><p><strong>Example:</strong></p><p><em>When rendering financial dashboards, serve </em><strong><em>pre-aggregated data models</em></strong><em> from the backend rather than pushing raw data to the front end for client-side calculation.</em></p><p><em>✅ </em><strong><em>Architectural Implication:</em></strong></p><p><em>Precompute complex aggregates and support progressive data loading.</em></p><blockquote><strong><em>“Architecture supports design; it doesn’t control it. But if the architecture blocks good design, you’ve already failed.”[1]</em></strong></blockquote><h3>🏗 UX Is an Architectural Concern — Not Just a UI Concern</h3><p>After digging through all these patterns, it becomes clear that UX isn’t something layered on top of architecture — it grows directly out of it. However, good architects know how to prevent UX concerns from dominating implementation details. This balance is crucial: implementation should focus on the internal architecture, while UX should inform the external experience without overshadowing the core design.</p><p>The decisions we make around:</p><ul><li>Service boundaries</li><li>Communication patterns</li><li>Error handling</li><li>Workflow coordination</li><li>Team structures</li></ul><p>…all directly shape how intuitive, predictable, and reliable the system feels to its users.</p><p>In many ways, <strong>architecture defines the ceiling for how good UX can ever be.</strong></p><h4>🎯Conclusion: Great UX Is Built into the Architecture</h4><p>At the end of the day, great UX isn’t just about beautiful screens — it’s about how your architecture enables clarity, stability, and trust throughout the entire system. <strong>Good architecture enables great UX.</strong></p><p><strong>🔮 What’s Next</strong></p><p>In the next article, I’ll shift gears again — diving into one of the most foundational aspects of architecture: <strong>State Management &amp; persistence</strong>. We’ll explore how state shapes workflows, coordination, failure handling, and even performance itself. Stay tuned. 👋</p><h3>📚 References</h3><ol><li>Srinath Perera, <em>Software Architecture and Decision-Making: Leveraging Leadership, Technology, and Product Management to Build Great Products</em>, 2023.</li><li>Robert C. Martin, <em>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</em>, Prentice Hall, 2017.</li><li>Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship, Prentice Hall, 2008.</li><li>Mark Richards and Neal Ford, <em>Fundamentals of software architecture: an engineering approach, 2020</em></li><li><a href="https://bytebytego.com/guides/orchestration-vs-choreography-microservices/">https://bytebytego.com/guides/orchestration-vs-choreography-microservices/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a58a42550711" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/architecture-meets-ux-designing-software-for-humans-not-just-machines-a58a42550711">🎯 Architecture Meets UX: Designing Software for Humans, Not Just Machines</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Coordination & Communication: Making Software Systems Work as One]]></title>
            <link>https://cudakara.medium.com/coordination-communication-making-software-systems-work-as-one-dbd53127e901?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd53127e901</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[software-coordination]]></category>
            <category><![CDATA[choreography]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 21:23:23 GMT</pubDate>
            <atom:updated>2025-06-07T21:23:23.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jk6CMnTHIbidseUetcAgQ.png" /></figure><p>In the first article, I explored how architecture begins with a mindset — shaped by trade-offs, questions, and mental models. Then, in the second part, I broke down how those architectural choices impact performance. In my third piece, I presented how classes, components, and systems should be structured and why it is so important in terms of architecture. Now, I want to turn to something just as critical but often underestimated: <strong>coordination and communication.</strong></p><p>In modern software systems — especially microservices — how components interact is just as important as how they’re built. This article focuses on the patterns, techniques, and architectural implications of communication, with lessons from real-world systems I’ve worked on, like our property management app and its direct debit flows.</p><h3>🔌 Communication in Software Systems: Sync, Async &amp; Events</h3><p>No matter how clean your code is or how well-structured your architecture might be — <strong>at the end of the day, services need to talk to each other</strong>. Communication is where design decisions become reality.</p><p>And just like in human communication, the <strong>how</strong> and <strong>when</strong> of these conversations between services matter deeply.</p><h4>1. 🔁 Synchronous Communication: The Classic Call-and-Response</h4><p>This is your traditional “request and response” flow — think HTTP calls, GraphQL queries, or gRPC endpoints. When <strong>Service A</strong> calls <strong>Service B</strong>, it waits for a reply.</p><h4>✅ When to Use It:</h4><ul><li>You need an immediate response (e.g., “Is this tenant eligible for a discount?”).</li><li>The caller must wait to proceed (e.g., verify credentials before login).</li><li>Simpler error handling with built-in retries or fallbacks.</li></ul><h4>❌ What to Watch Out For:</h4><ul><li>Tight coupling: A failure in Service B breaks Service A.</li><li>Latency: Every extra hop adds delay to the user experience.</li><li>Scalability limits: You’re bound by how many threads can wait.</li></ul><blockquote>Eg: In the property management system, when the frontend calls the payment service to initiate a one-time debit, it uses synchronous HTTP with retries. The result is shown to the user instantly.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcnyHLk8eUj-SCmwslfCoA.png" /><figcaption>Sync vs Async communication</figcaption></figure><h4>2. 📨 Asynchronous Communication: Fire-and-Forget</h4><p>Async communication breaks the expectation of immediate replies. Here, <strong>Service A</strong> sends a message (via queue or stream), and moves on. <strong>Service B</strong> picks it up later.</p><p>This is especially useful in workflows where:</p><ul><li>The result isn’t needed immediately (e.g., sending a confirmation email).</li><li>Latency doesn’t block the user (e.g., audit logs, metrics).</li><li>You want to decouple services.</li></ul><h4>✅ Benefits:</h4><ul><li>Loose coupling between services</li><li>More resilient and scalable</li><li>Allows parallel processing</li></ul><h4>❌ Trade-Offs:</h4><ul><li>Harder to debug</li><li>Delayed error visibility</li><li>Requires careful retry, deduplication, and ordering</li></ul><blockquote>Eg: When a tenant sets up direct debit, we emit an event like MandateSetupCompleted. Services like invoicing and notifications listen for this and react. If the invoice generator is down, it picks up the event when it comes back.</blockquote><h4>3. 🧭 Event-Driven Communication: Let the System React</h4><p>Events are a <strong>form of asynchronous communication</strong>, but they carry more semantic meaning. An <strong>event</strong> says: “Something happened” — and any number of services can choose to respond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxMqHbYZAjtH6HCF8vM5AA.png" /></figure><p>Event-driven systems work well when:</p><ul><li>You want loose coupling and high flexibility</li><li>Workflows can evolve organically</li><li>Multiple services are interested in a single outcome</li></ul><p><strong>🔍 Event vs Command:</strong></p><ul><li><strong>Command:</strong> Do X → targeted (e.g., POST /send-email)</li><li><strong>Event:</strong> X happened → broadcast (e.g., InvoiceCreated)</li></ul><blockquote>Eg: When InvoiceCreated is emitted:<br>- Payment service reserves the amount.<br>- Email service sends a billing notification.<br>- Analytics service logs monthly revenue.</blockquote><blockquote>None of these need to know about each other. They just react.</blockquote><h3>🧱 Communication about the system — → Well-defined API Contracts Are the Backbone of Coordination</h3><p>In my experience(time-wise quite small but I have made mistakes and faced issues more than enough to understand this) and from my learnings, one of the easiest ways to introduce bugs, misunderstandings, or brittle integrations is to have <strong>unclear communication contracts</strong> between services. Whether you use REST, GraphQL, or event-driven architecture with Kafka or SNS, <strong>explicit, validated, and versioned contracts</strong> are essential.</p><p>When services evolve independently, loosely defined contracts can create unexpected behaviour and hidden dependencies. That’s why I treat contracts as <strong>first-class architectural artefacts</strong>.</p><p>Here’s how we make this real:</p><ul><li>🧾 <strong>Shared Schemas</strong> — All event payloads and API inputs/outputs are defined using shared TypeScript schemas and published from a central repo.</li><li>🧪 <strong>Validation with Zod</strong> — We use runtime validators like <a href="https://github.com/colinhacks/zod">Zod</a> to enforce schema correctness and guard against malformed data.</li><li>📦 <strong>Versioned APIs and Events</strong> — Breaking changes are introduced in v2 payloads, never by silently changing v1. This ensures backward compatibility.</li></ul><p><strong>🔍 Real Example — Invoice Events in the Property System</strong></p><p>When the <strong>invoice service</strong> emits an InvoiceCreated event, services like <strong>payment</strong>, <strong>email</strong>, and <strong>accounting</strong> listen to it. We standardize the payload to:</p><pre>{<br>  tenantId: string;<br>  amount: number;<br>  currency: &#39;EUR&#39; | &#39;USD&#39;;<br>  dueDate: string;<br>}</pre><p>By keeping this contract stable and validated across services, new listeners can plug in without fear of breaking the system — or misinterpreting the intent.</p><h4>🧠 Conway’s Law: People Mirror Architecture</h4><p>One thing that becomes obvious as systems scale is that <strong>organizational design bleeds into your architecture</strong>. This is Conway’s Law in action:</p><blockquote>“Organizations which design systems … are constrained to produce designs which are copies of the communication structures of these organizations.”</blockquote><blockquote><em>— Melvin Conway, 1968</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H4OFyhzHvmG-rotK_tlnw.png" /><figcaption>Conway’s law in action</figcaption></figure><h4>💥 Why This Matters in Practice</h4><p>If your <strong>data pipeline</strong> is shared across 4 different teams (data, backend, infra, QA), coordination will suffer unless ownership and communication are aligned.</p><p>In the <strong>direct debit onboarding flow</strong> we built, we saw issues like:</p><ul><li>Misfired triggers when onboarding and payment teams weren’t aligned.</li><li>Redundant state handling when both invoice and email services tried to act on the same event independently.</li><li>Delays and race conditions because no one “owned” the full flow.</li></ul><h4>✅ What Works Instead</h4><ul><li><strong>Align team boundaries with service boundaries.</strong> If one team owns the onboarding flow, they should own the workflow logic, not just the service code.</li><li><strong>Reduce cross-boundary coordination.</strong> Use APIs and events to decouple where needed, but keep workflows simple and team-centric.</li><li><strong>Use architecture to support autonomy.</strong> Choreography works best when teams can act independently; and orchestration when tight control is needed.</li></ul><h4>🎯 Why This Is Core to Architecture</h4><p>Architecture isn’t just code and infrastructure[4] — it’s the <strong>contract between people, teams, and technology</strong>. If your system is brittle, hard to change, or constantly misbehaving, it’s often a reflection of:</p><ul><li>Fuzzy ownership</li><li>Poor contracts</li><li>Misaligned coordination models</li></ul><p>Fixing these improves not just the system, but also how people <strong>collaborate</strong>, <strong>build</strong>, and <strong>ship software</strong>.</p><p>Effective communication in software systems goes beyond APIs and message brokers — it’s about establishing clarity, consistency, and ownership across teams and services. Whether using synchronous calls, asynchronous messaging, or event-driven patterns, well-defined contracts and aligned team structures are essential to avoid brittle integrations and hidden failures. But communication alone isn’t enough. To truly make systems work as a cohesive whole, we need coordination — how services sequence, react and recover together. That’s where coordination comes in, and that’s exactly what we’ll explore next.</p><h3>🧩 What Is Coordination, Really?</h3><p>From my experience, <strong>coordination</strong> is one of those invisible forces in software architecture — we don’t always see it in code reviews or diagrams, but it shows up when systems break, workflows fail, or responsibilities become unclear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*WB2Xz4Ym698TU7SySmFoQw.png" /></figure><p>At its core, <strong>coordination is the logic that connects individual services into a cohesive system[1].</strong> It’s how we make sure things happen in the right order, with the right context, and with fallback strategies when something goes wrong.</p><p>But this goes beyond REST calls or events. Coordination is how your architecture expresses responsibility, recoverability, and evolution[3]. It’s how services align with the business. When done poorly, it leads to broken flows, tight coupling, or systems that can’t scale without falling apart.</p><h4>🔄 It’s More Than Just “Calling Other Services”</h4><p>People often think coordination is just making an API call from service A to service B. But real-world coordination is about managing:</p><ul><li><strong>Order of execution</strong> (What needs to happen first?)</li><li><strong>State propagation</strong> (How does each step know what happened before?)</li><li><strong>Failure recovery</strong> (What do we do if something fails midway?)</li><li><strong>Timing and triggering</strong> (Is this action time-based, event-based, or on-demand?)</li><li><strong>Ownership</strong> (Who is responsible for making decisions and ensuring the workflow is completed?)</li></ul><p>Let’s take a real-world example from the <strong>property management system</strong> I work on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hr8WwqHJhh87HBhln32cw.png" /></figure><p><strong>Without coordination</strong>, we might have:</p><ul><li>The onboarding service registers the user.</li><li>The payment service waiting to receive a mandate.</li><li>The invoice service preparing a bill.</li><li>The email service is unsure when to notify.</li></ul><p>Each part works in isolation — but nothing connects them. So, one missing piece causes the whole user experience to fall apart.</p><p>Now, <strong>with proper coordination</strong>, the system knows:</p><ul><li>When to trigger mandate setup (after onboarding).</li><li>When to wait for bank confirmation before issuing invoices.</li><li>How to notify the tenant once the mandate is active and the invoice is ready.</li></ul><p>And most importantly: <strong>who is responsible for ensuring this flow completes</strong>?</p><p>Absolutely! Here’s a more descriptive, refined version of the <strong>“🚦 4 Architectural Approaches to Coordination”</strong> section — incorporating insights and ideas inspired by <strong>Srinath Perera</strong>, <strong>Mark Richards</strong>, and <strong>Neal Ford</strong>. It explains not just the patterns but also the <strong>decision-making frameworks</strong> behind choosing each.</p><h3>🚦 Architectural Approaches to Coordination</h3><p>Coordination isn’t just a technical design decision — it’s deeply tied to <strong>team structure, ownership, evolution strategy, and product needs</strong>. Over time, I’ve noticed and learned that systems typically evolve toward one of four primary coordination styles[1].</p><p>Each of these has strengths, trade-offs, and use cases. The key is to <strong>match your coordination approach with your system’s complexity and change dynamics</strong>, a principle echoed in both <em>Software Architecture and Decision-Making</em> by Srinath Perera[1] and <em>Fundamentals of Software Architecture</em> by Mark Richards and Neal Ford[4].</p><p>Let’s break them down:</p><h3>1. 🧍 Client-Driven Flow</h3><p>In this approach, the front end(or the client) <strong>controls the workflow</strong> by calling each backend service directly in sequence. It’s simple but puts coordination responsibility on the client. This is the most commonly used approach and most of the web services and command line applications are built with this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Gi-Zld-1Hgtr9KfZrvI4g.png" /><figcaption>A system that uses Client Driven Flow</figcaption></figure><blockquote>🧠 <strong>Use Case</strong>: In our property management system, during tenant onboarding, the user goes through several steps:<br> 1.Accepts the lease<br> 2. Uploads documents<br> 3. Sets up direct debit</blockquote><blockquote>The client application coordinates these steps through REST APIs.</blockquote><p>✔ <strong>Pros</strong>:</p><ul><li>Transparent and simple to build</li><li>Good for tightly coupled UIs (e.g., onboarding wizards)</li></ul><p>❌ <strong>Cons</strong>:</p><ul><li>Harder to test and change flows</li><li>Business logic leaks into the frontend</li><li>Poor error recovery if clients disconnect or mis-sequence steps</li></ul><h3>2. 🧩 Dedicated Service for Workflow</h3><p>In this architecture, you create a <strong>custom coordination service ( a dedicated service) </strong>that manages the flow of business logic by interacting with other services[1]. It’s like a lightweight coordinator embedded in your backend domain. This could be a separate microservice which controls all the data flows as an admin[3]. For this, we use asynchronous communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vG9aAejSQZ4yn8GeaFNjWQ.png" /><figcaption>A system that uses Dedicated Service for coordination (just managing but not deciding or ordering)</figcaption></figure><blockquote>🧠 <strong>Use Case</strong>: We implemented a coordination service for <strong>tenant verification and mandate direct debit setup</strong>. It managed the sequence of identity verification, mandate requests, and invoice pre-generation without relying on the front end. Baiscally this flow can triggered from different other events or from cron jobs on schedule.</blockquote><p>✔ <strong>Pros</strong>:</p><ul><li>Central point to manage logic</li><li>Easier testing and reuse</li><li>Separates workflow concerns from UI and individual services</li></ul><p>❌ <strong>Cons</strong>:</p><ul><li>Can become bloated over time</li><li>Could become a single point of failure for the system.</li><li>Risk of becoming a “god service” if not scoped well</li><li>The performance of the system will based on this single service.</li></ul><h3>3. 🛠 Middleware/Platform-Oriented Coordination</h3><p>In this approach, we will have a separate middleware or a platform to fully coordinate the data and execution flows of the system[2]. In this approach,h this coordination dictates the decisions of workflows like execution order, logging and queueing. This is where <strong>coordination is externalized to platforms</strong> like Step Functions, Airflow, or Dagster.</p><h4>🧠 Orchestration vs. Choreography (The Big Choice)</h4><p>These two aren’t just implementation styles — they’re <strong>philosophical approaches</strong> to architecture. They define how ownership, change, and communication evolve in a distributed system.</p><h4>1. Orchestration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RbzA9vJmbNU2PRlWIARdQ.png" /></figure><p>A central controller (orchestrator) manages the entire workflow, directing each service on what to do and when to do it.</p><p>Orchestration works differently from other coordination styles. In this pattern, a <strong>central orchestrator takes full control</strong> of the workflow. It’s responsible for calling each service, managing the order of operations, handling errors, and even coordinating transactions across services. You can think of it like a <strong>conductor in a symphony</strong> — directing when and how each musician (or service) plays their part to create a unified performance.</p><p>At every step, the orchestrator waits for confirmation before proceeding to the next service, ensuring the workflow stays consistent and errors are handled centrally. This kind of control is especially useful when <strong>multiple dependent steps must succeed for the process to be valid</strong>, such as financial setups or legal document submissions.</p><p><strong>Advantages of Orchestration<br></strong>✔ Centralized Workflow<br>✔ Error Handling &amp; Recovery<br>✔ State Management</p><p><strong>Disadvantages of Orchestration<br></strong>❌ Potential Bottlenecks.<br>❌ Higher Service Coupling</p><p><strong><em>Example</em></strong><em>: A centralized ETL pipeline that controls data extraction, transformation, and loading.</em></p><p><strong>How Does Orchestration Work?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkG134KZrWvIGw5AKrJtWw.png" /></figure><ul><li>An orchestrator component oversees the workflow, making decisions and directing services.</li><li>Each service handles its tasks but relies on the orchestrator for coordination.</li><li>If something goes wrong (e.g., mapping fails, stock runs out), the orchestrator decides what happens next.</li></ul><p><strong>🔧 Industry &amp; Cloud Tools that Support Orchestration:</strong></p><p><em>• </em><strong><em>AWS Step Functions</em></strong><em> — Serverless state machine that manages service calls, retries, and branching.<br> • </em><strong><em>Azure Durable Functions </em></strong><em>— A code-based orchestrator built on Azure Functions.<br> • </em><strong><em>Dagster</em></strong><em> — A powerful orchestration platform with a SAAS version.<br> •</em><strong><em> Apache Airflow </em></strong><em>— Used widely for data workflows, ETL orchestration, and more.<br> • </em><strong><em>Prefect</em></strong><em>— A self-hosted orchestration platform that provides a complete orchestration platform for your workflows</em></p><h4><em>2. Choreography</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cSScu4GC2gZFOcM_ljKUA.png" /></figure><p>In a <strong>choreographed architecture</strong>, there’s no central authority directing the flow. Instead, each service <strong>knows its role</strong>, listens for relevant events, and reacts accordingly. It’s a model where coordination emerges organically from event-based interactions between services.</p><p>Think of it like a <strong>dance performance</strong>. A choreographer might define the overall routine, but once the music starts, each dancer (or service) performs their moves independently — <strong>in sync, but without real-time direction</strong>. The flow depends on shared understanding, not centralized control.</p><p><strong>Advantages of Choreography<br></strong>✔ Responsiveness<br>✔ Scalability<br>✔ Service Decoupling</p><p><strong>Disadvantages of Choreography<br></strong>❌ No Central Workflow Owner<br>❌ State Management Issues — Since there’s no central coordinator, tracking the progress of workflows is more difficult.<br>❌ Complex Error Handling<br>❌ Difficult Recoverability</p><p><strong>How Does Choreography Work?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Esak8S0msGX8J8PMMAj9-A.png" /></figure><ul><li>No central controller — Services act independently and communicate through events.</li><li>Event-driven — When one service completes a task, it triggers an event for the next service to pick up.</li><li>Flexible and scalable — Since there’s no single point of control, services can be easily added or modified.</li></ul><p>🔧 <strong>Industry &amp; Cloud Tools that Enable Choreography:</strong></p><ul><li><strong><em>Amazon EventBridge</em></strong><em> / </em><strong><em>SNS + SQS</em></strong><em> — Event buses and messaging for loosely coupled systems</em></li><li><strong><em>Apache Kafka</em></strong><em> — High-throughput event streaming for reactive services</em></li><li><strong><em>NATS</em></strong><em> — Lightweight messaging platform ideal for real-time choreography</em></li><li><strong><em>Google Pub/Sub</em></strong><em> — Scalable event ingestion and delivery</em></li></ul><p>In modern <strong>microservices-based systems</strong>, coordination is not just a design choice — it’s a foundational need. As we break down monoliths into smaller services, we also distribute responsibility[2]. That’s where <strong>orchestration</strong> and <strong>choreography</strong> become vital patterns. Both are widely adopted — sometimes even <strong>combined</strong> — depending on the use case, system maturity, and operational needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9Ur0DTfhDbVfmeOg38bOA.png" /><figcaption>Comparison between Choreography and Orchestration</figcaption></figure><h3>🧠 My Takeaway</h3><p>What I’ve learned from working across these patterns is that there’s <strong>no silver bullet</strong>. Coordination is a strategic choice.</p><p>If you need:</p><ul><li>Tight control, go orchestration.</li><li>Speed and scale, go choreography.</li><li>Simplicity, use client-driven flows.</li><li>Modularity with control, use dedicated workflow services.</li></ul><p>But always <strong>match the coordination model to the domain complexity</strong> and <strong>your team’s operational maturity[1]</strong>.</p><h4>✅ <strong>Conclusion: Coordination is the Invisible Glue</strong></h4><p>If architecture is about shaping systems, then coordination is what makes those systems <em>move</em> in harmony. We’ve explored how communication becomes the lifeline of service interactions — and how <strong>coordination patterns like orchestration and choreography</strong> define not just <em>how</em> services connect, but <em>how well</em> they work together. Whether you’re using client-driven flows, dedicated workflow services, or full orchestration platforms like Dragster or Step Functions, what matters most is <strong>clarity of ownership, flow, and contracts[4]</strong>.</p><p>As systems scale, coordination becomes less about infrastructure and more about <strong>intentional design choices[2]</strong>. Aligning your team boundaries, choosing the right coordination model for the job, and treating communication as a first-class citizen — these are the real differentiators in successful software systems.</p><p><strong><em>✨ What’s Next: UX, Flow, and How Architecture Meets the User</em></strong></p><p>In the next article, I’ll switch gears and look at something equally architectural — but through a user’s lens: <strong>User Experience (UX)</strong>. Stay tuned. 👋</p><h3>📚 References</h3><ol><li>Srinath Perera, <em>Software Architecture and Decision-Making: Leveraging Leadership, Technology, and Product Management to Build Great Products</em>, 2023.</li><li>Robert C. Martin, <em>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</em>, Prentice Hall, 2017.</li><li>Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship, Prentice Hall, 2008.</li><li>Mark Richards and Neal Ford, <em>Fundamentals of software architecture: an engineering approach, 2020</em></li><li><a href="https://bytebytego.com/guides/orchestration-vs-choreography-microservices/">https://bytebytego.com/guides/orchestration-vs-choreography-microservices/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd53127e901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Code and Component Structure in Practice: Bridging Design Principles with Real-World…]]></title>
            <link>https://cudakara.medium.com/code-and-component-structure-in-practice-bridging-design-principles-with-real-world-b66b8728df26?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/b66b8728df26</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[code-structure]]></category>
            <category><![CDATA[system-structure]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 14:20:33 GMT</pubDate>
            <atom:updated>2025-06-01T14:20:33.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrjLJNDGAItUKLWzKUmpCA.png" /></figure><h3><strong>🧱 Code and Component Structure in Practice: Bridging Design Principles with Real-World Architecture</strong></h3><p>In the first article, we explored foundational thinking with <a href="https://cudakara.medium.com/understanding-and-designing-software-architecture-through-mental-models-a-pragmatic-guide-for-4cc2942c202b"><em>mental models</em> for architectural decisions</a>. In the second, we broke down how those early design choices shape <a href="https://cudakara.medium.com/software-architecture-and-system-performance-a9889624b727">system performance</a>.</p><p>This third instalment brings it all together — focusing on <strong>how we structure code and components</strong> to build systems that are scalable, testable, and maintainable over time. From SOLID principles[3] to component cohesion and boundaries, this guide offers a pragmatic approach that every engineer or architect can apply. Let’s dive in.</p><h3>👋 Introduction</h3><p>In software engineering, how we structure <strong>code and components</strong> fundamentally shapes the <strong>scalability</strong>, <strong>maintainability</strong>, and <strong>clarity</strong> of a system. Whether we’re designing a microservice, building a frontend UI module, or maintaining a monolithic backend, <strong>respecting boundaries and applying solid design principles[2]</strong> is crucial for delivering reliable and adaptable software. As we all know code structure directly impacts our daily life and work as software developers.</p><p>Drawing from my experience and various sources, this article provides a practical overview of component structuring, code boundaries, and how to align implementation with SOLID principles and component design heuristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*z6tVzhtLuGd7J3hHF9falw.png" /><figcaption>Sample code base</figcaption></figure><h3>📐 Why Structure Matters</h3><p>Code structure is more than just style — it directly affects how your system evolves. Poor structure increases technical debt and makes future changes painful, whereas good structure enables agility and long-term success. Here are some observations, with examples from my property management solution:</p><h4>🚫 Poor Code Organization Leads To:</h4><ol><li><strong>Tight Coupling &amp; Ripple-Effect Bugs</strong></li></ol><blockquote>An update to <strong>TenantService</strong> (e.g., modifying tenant payment status tracking) inadvertently disrupts <strong>InvoiceService</strong>. This issue stems from both services’ reliance on a shared, overblown utils.ts file, which contains a mix of business logic and data access functions. Such tight coupling inevitably results in unintended side effects and brittle behaviour.</blockquote><p><strong>2. Painful Deployments and Difficult Reuse</strong></p><blockquote>Updating logic to handle late payment penalties in the <strong>LeaseController</strong> module requires deploying the entire <strong>PropertyModule</strong>, including unrelated classes like <strong>InspectionScheduler</strong>. The lack of modular separation increases deployment risk and slows down development velocity.</blockquote><p><strong>3. Inefficient Collaboration in Growing Teams</strong></p><blockquote>Two engineers updating different parts of the same <strong>PropertyManagementService</strong> file (one for <strong>lease renewals</strong>, the other for <strong>maintenance scheduling</strong>) constantly cause merge conflicts, because unrelated responsibilities are housed together with no clear ownership boundaries.</blockquote><h3>✅ Well-Structured Code Enables:</h3><ol><li><strong>Modularity and Testability</strong></li></ol><blockquote>Encapsulating lease renewal logic into a separate <strong>LeaseRenewalService</strong> allows for isolated testing of edge cases like date overlaps and rate adjustments — without loading unrelated dependencies like <strong>tenant communication</strong> logic.</blockquote><p><strong>2. Faster Onboarding and Safer Changes</strong></p><blockquote>A new developer joining the project can quickly grasp the codebase because it’s organized into clearly named domains like <strong>Tenants</strong>/, <strong>Leases</strong>/, and <strong>Maintenance</strong>/, each containing its own controller, service, and test files.</blockquote><p><strong>3. Independent Releases and Clear Ownership</strong></p><blockquote>The team managing <strong>PaymentService</strong> can deploy improvements to payment method validations or third-party gateway integrations without touching or affecting the <strong>PropertyListingService</strong> — thanks to clear boundaries and API contracts.</blockquote><p>This is a very general and high-level idea of how code structure can affect our day-to-day life for better or worse. But it explains a lot and makes a lot of sense how code structure affects everything including the architecture of the system.</p><h3>📚 A Real-World Lens: Lessons from</h3><h3>The Phoenix Project[5]</h3><p>To bring this idea into perspective, I often reflect on the core message of <em>The </em><strong><em>Phoenix Project</em></strong><em>[5]</em> by Gene Kim, Kevin Behr, and George Spafford. Though framed as a novel, it’s one of the most impactful reads in the DevOps space — and a powerful illustration of why <strong>code and system structure matter deeply to our daily work as engineers</strong>.</p><p>The story follows a company plagued by missed deadlines, constant outages, and a culture of chaos. At the heart of it? <strong>A poorly structured codebase with no clear boundaries</strong>, buried dependencies, and tightly coupled systems. Engineers are stuck in a reactive loop — spending their days firefighting, chasing elusive bugs, and dealing with the fallout of every small change cascading into system-wide failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qrVTJz5WAlajMA8ai3gaQ.jpeg" /></figure><p>This depiction might feel familiar to many of us. It shows how disorganized architecture doesn’t just make systems fragile — it makes <strong>engineering itself unsustainable </strong>and<strong> miserable</strong>. Developers lose control over the very systems they’re supposed to be building, and the day-to-day work becomes exhausting and demoralizing[5]. Every small change feels risky, deployments become dreaded events and meaningful progress stalls.</p><p>But what makes <em>The Phoenix Project</em> such a valuable reference is how it pivots. Once the team embraces principles like <strong>modularity</strong>, <strong>flow</strong>, and <strong>ownership</strong>, things begin to shift. They start by <strong>refactoring toward clearer component boundaries</strong>, <strong>separating responsibilities</strong>, and <strong>reducing reliance on brittle, shared logic</strong>. As a result:</p><ul><li>Outages drop</li><li>Deployments become smoother</li><li>Teams reclaim the space to focus on real innovation</li></ul><p>This shift is architectural at its core. As the system moves from a tangled monolith to a more modular and decoupled structure, the architecture itself becomes an <strong>enabler</strong>, not a blocker. It allows the organization to scale, respond to change with confidence, and support multiple teams working in parallel without constant collisions.</p><p>It’s a reminder that <strong>code structure isn’t just a backend concern — it’s a foundational architectural concern</strong>. The way we divide responsibilities, define boundaries and manage dependencies in code directly shapes the broader <strong>software architecture</strong> and the quality of life for the teams maintaining it. That’s why I believe <em>The Phoenix Project</em> remains such a relevant and relatable example when discussing how thoughtful design decisions at the code and component level lead to long-term architectural success.</p><p>Our discussion will journey through code structuring, starting from the granular <strong><em>file/class level</em></strong>, moving up to <strong><em>modules and components</em></strong>, and culminating at the <strong><em>system level</em></strong>. This bottom-up approach is vital for understanding the holistic nature of system architecture.</p><h3>🧭 Guiding Principles for Structuring Code to Build Effective Mental Models</h3><h3>✅ SOLID Principles</h3><p>The SOLID principles, introduced by Robert C. Martin (Uncle Bob)[2], provide a foundation for creating maintainable and extensible software systems. Let’s explore each principle with examples pertinent to a property management context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0rbw4OugArLAaiZe0fk8A.png" /></figure><h4>1. Single Responsibility Principle (SRP)</h4><p><strong>Definition</strong>: A class should have only one reason to change, meaning it should encapsulate only one responsibility. Basically, Each class or module should focus on a single task or functionality.</p><p><strong>Example</strong>:</p><ul><li><strong>Violation →</strong><em> A </em><strong><em>TenantManager</em></strong><em> class that handles tenant data retrieval, lease agreement processing, and payment calculations.</em></li><li><strong>Adherence → </strong><em>Separating concerns into distinct classes: </em><strong><em>TenantRepository</em></strong><em> for data access, </em><strong><em>LeaseProcessor</em></strong><em> for handling lease agreements and </em><strong><em>PaymentCalculator</em></strong><em> for computing payments.</em></li></ul><pre>// Violation<br>class TenantManager {<br>  getTenant(id: string) { /* ... */ }<br>  processLease(tenantId: string) { /* ... */ }<br>  calculatePayment(tenantId: string) { /* ... */ }<br>}<br><br>// Adherence<br>class TenantRepository {<br>  getTenant(id: string) { /* ... */ }<br>}<br><br>class LeaseProcessor {<br>  processLease(tenantId: string) { /* ... */ }<br>}<br><br>class PaymentCalculator {<br>  calculatePayment(tenantId: string) { /* ... */ }<br>}</pre><h4>2. Open/Closed Principle (OCP)</h4><p><strong>Definition</strong>: Software entities should be open for extension but closed for modification[3]. In a nutshell, You should be able to add new features or behaviours without altering existing code.</p><p><strong>Example</strong>:</p><ul><li><strong>Violation →</strong><em>Modifying a </em><strong><em>NotificationService</em></strong><em> class each time a new notification type (email, SMS, push) is added.</em></li><li><strong>Adherence →</strong> <em>Defining a Notification interface with implementations like </em><strong><em>EmailNotification</em></strong><em>, </em><strong><em>SMSNotification</em></strong><em>, and </em><strong><em>PushNotification</em></strong><em>. The </em><strong><em>NotificationService</em></strong><em> can then work with the interface, allowing new types to be added without altering existing code.</em></li></ul><pre>// Violation<br>class NotificationService {<br>  sendNotification(type: string, message: string) {<br>    if (type === &#39;email&#39;) { /* ... */ }<br>    else if (type === &#39;sms&#39;) { /* ... */ }<br>    // Adding a new type requires modifying this method<br>  }<br>}<br><br>// Adherence<br>interface Notification {<br>  send(message: string): void;<br>}<br><br>class EmailNotification implements Notification {<br>  send(message: string) { /* ... */ }<br>}<br><br>class SMSNotification implements Notification {<br>  send(message: string) { /* ... */ }<br>}<br><br>class NotificationService {<br>  constructor(private notifier: Notification) {}<br>  send(message: string) {<br>    this.notifier.send(message);<br>  }<br>}</pre><h4>3. Liskov Substitution Principle (LSP)</h4><p><strong>Definition</strong>: Subtypes must be substitutable for their base types without altering the correctness of the program. Simply, objects of a superclass should be replaceable with objects of a subclass without affecting the program’s correctness.</p><p><strong>Example</strong>:</p><ul><li><strong>Violation → </strong><em>A </em><strong><em>PremiumTenant</em></strong><em> subclass that throws exceptions when certain base class methods are called, breaking expected behaviour.</em></li><li><strong>Adherence →</strong> <em>Ensuring that </em><strong><em>PremiumTenant</em></strong><em> overrides base class methods appropriately, maintaining consistent behaviour.</em></li></ul><pre>// Violation<br>class Tenant {<br>  requestMaintenance() { /* ... */ }<br>}<br><br>class PremiumTenant extends Tenant {<br>  requestMaintenance() {<br>    throw new Error(&quot;Premium tenants have a different process.&quot;);<br>  }<br>}<br><br>// Adherence<br>interface MaintenanceRequester {<br>  requestMaintenance(): void;<br>}<br><br>class RegularTenant implements MaintenanceRequester {<br>  requestMaintenance() { /* ... */ }<br>}<br><br>class PremiumTenant implements MaintenanceRequester {<br>  requestMaintenance() { /* ... */ }<br>}</pre><h4>4. Interface Segregation Principle (ISP)</h4><p><strong>Definition</strong>: Clients should not be forced to depend on interfaces they do not use[2]. Simply put, create specific interfaces for distinct functionalities so that implementing classes only needs to be concerned with the methods relevant to them. ISP promotes decoupling and enhances system flexibility</p><p><strong>Example</strong>:</p><ul><li><strong>Violation →</strong><em> A </em><strong><em>PropertyOperations</em></strong><em> interface that includes methods for leasing, maintenance, and inspections, forcing classes to implement irrelevant methods.</em></li><li><strong>Adherence →</strong> <em>Splitting into specific interfaces like </em><strong><em>LeasingOperations</em></strong><em>, </em><strong><em>MaintenanceOperations</em></strong><em>, and </em><strong><em>InspectionOperations</em></strong><em>, allowing classes to implement only what they need.</em></li></ul><pre>// Violation<br>interface PropertyOperations {<br>  leaseProperty(): void;<br>  scheduleMaintenance(): void;<br>  conductInspection(): void;<br>}<br><br>class MaintenanceTeam implements PropertyOperations {<br>  leaseProperty() { /* Not applicable */ }<br>  scheduleMaintenance() { /* ... */ }<br>  conductInspection() { /* Not applicable */ }<br>}<br><br>// Adherence<br>interface LeasingOperations {<br>  leaseProperty(): void;<br>}<br><br>interface MaintenanceOperations {<br>  scheduleMaintenance(): void;<br>}<br><br>interface InspectionOperations {<br>  conductInspection(): void;<br>}<br><br>class MaintenanceTeam implements MaintenanceOperations {<br>  scheduleMaintenance() { /* ... */ }<br>}</pre><h4>5. Dependency Inversion Principle (DIP)</h4><p><strong>Definition</strong>: High-level modules should not depend on low-level modules; both should depend on abstractions[3]. Depend on abstractions (interfaces) rather than concrete implementations to reduce coupling between components[1].</p><p><strong>Property Management Example</strong>:</p><ul><li><strong>Violation →</strong> <em>A </em><strong><em>LeaseService</em></strong><em> class directly instantiates a </em><strong><em>DatabaseConnector</em></strong><em>, creating tight coupling.</em></li><li><strong>Adherence →</strong> <em>Defining an </em><strong><em>IDatabaseConnector</em></strong><em> interface that LeaseService depends on, with </em><strong><em>DatabaseConnector</em></strong><em> implementing this interface. This allows for easier substitution and testing.</em></li></ul><pre>// Violation<br>class LeaseService {<br>  private dbConnector = new DatabaseConnector();<br>  // ...<br>}<br><br>// Adherence<br>interface IDatabaseConnector {<br>  connect(): void;<br>}<br><br>class DatabaseConnector implements IDatabaseConnector {<br>  connect() { /* ... */ }<br>}<br><br>class LeaseService {<br>  constructor(private dbConnector: IDatabaseConnector) {}<br>  // ...<br>}</pre><h4>⁉️ Why SOLID Still Matters</h4><p>The SOLID principles aren’t just academic guidelines — they’re pragmatic tools for building resilient, adaptable systems that can grow with evolving business needs. So SOLID principles are guidelines for good architecture.</p><p>As experts emphasize, architectural clarity starts with disciplined design[1] — and SOLID is often the first step in that discipline. Ultimately, these principles are about building <strong>software that lasts.</strong></p><p>As we move forward in this article, we’ll scale these ideas beyond classes and into <strong>components</strong>, where modular design and architectural boundaries amplify the same goals: clarity, adaptability, and long-term sustainability.</p><h3>🧩 Component Design Principles</h3><p>As our software systems evolve beyond individual classes and functions, the need for thoughtful organization at the component level becomes paramount. While SOLID principles guide us in crafting robust and maintainable classes, component design principles help us structure these classes into cohesive, reusable, and scalable modules.</p><p>In the context of my example property management system, components might include modules like <em>TenantManagement</em>, <em>LeaseProcessing</em>, or <em>MaintenanceScheduling</em>. Properly designing these components ensures that our system remains adaptable to changing requirements, facilitates team collaboration, and simplifies maintenance.</p><p>Component design principles are broadly categorized into:</p><ol><li><strong>Cohesion Principles</strong>: Determining how classes should be grouped within components to ensure they change together and serve a unified purpose[2].</li><li><strong>Coupling Principles</strong>: Guiding how components should interact with each other to minimize dependencies and enhance flexibility[2].</li></ol><p>In my journey as a software engineer, I’ve come to appreciate that component design principles are not just theoretical constructs — they are practical tools that profoundly impact the quality and sustainability of our systems.</p><h3>📦 Cohesion Principles</h3><p>These principles focus on the internal organization of components, ensuring that classes within a component are related and change for similar reasons.</p><h4>1. REP — Release Reuse Equivalency Principle</h4><p>A component should not be reused unless it can be independently released. Classes and modules should belong to cohesive groups — independently versioned and released. Only reuse things you can version and release without dragging the whole system with it.</p><blockquote>Eg: A <strong>PaymentProcessing module</strong> that handles transactions, invoices, and refunds should be releaseable on its own — maybe it’s reused by both the Tenant Portal and Admin Dashboard.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaGR5EdGtg9Jg9j6SvjHMA.png" /></figure><h4>2. CCP — Common Closure Principle</h4><p>Group classes that change for the same reason. Don’t force unrelated changes into a single release. Gather into components those classes that change for the same reason and at the same time.<em> </em>Simply put, If they change together, keep them together.</p><blockquote>Eg: <strong>LeaseAgreementService</strong> and <strong>RentPolicyValidator</strong> often change due to rent regulation updates. Keeping them in the same <strong>LeaseManagement</strong> component ensures they’re tested, deployed, and versioned together.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f96cd_AWaNEdc4gpFEWzQA.png" /></figure><ul><li>Here’s the timeline diagram showing two different change patterns:<br><em> — → </em><strong><em>Lease logic classes</em></strong><em> (e.g., LeaseAgreementService, RentPolicyValidator) change in </em><strong><em>Jan, Mar, and May</em></strong><em>.<br> — → </em><strong><em>Tenant communication classes</em></strong><em> (e.g., TenantEmailService, NotificationScheduler) change in </em><strong><em>Feb and Apr</em></strong><em>.</em></li></ul><h4>3. CRP — Common Reuse Principle</h4><p>Don’t depend on components you don’t use. Only depends on what you actually need. Don’t force users of a component to depend on things they don’t use. In summary, Don’t include extra baggage.</p><blockquote>Eg: Your <strong>InvoiceService</strong> needs only email notifications, not SMS. Depending on a bulky <strong>NotificationService</strong> with all types included would pull in code and responsibilities you don’t need.</blockquote><h4>⚖️ Balancing REP, CCP, and CRP</h4><p><em>“REP, CCP, and CRP are often in conflict — focusing on one can violate the others.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*9sOuppNio6jdFJOCskxMqA.png" /><figcaption>Cohesion priciples for component structuring</figcaption></figure><p><strong>📌 What This Means</strong>:</p><ul><li><strong>Too many micro-components</strong> = harder to manage (violates CCP)</li><li><strong>Too few components</strong> = too much-unused functionality pulled in (violates CRP)</li><li><strong>Too much reuse</strong> = accidental tight coupling (violates REP)</li></ul><p>A good architect balances all three, adapting based on system context, team ownership, and future change expectations.</p><h3>🔗 Coupling Principles</h3><p>These principles address the relationships between components, aiming to minimize interdependencies and enhance system flexibility.</p><p>These principles are critical for keeping systems modular and avoiding the domino effect of tightly coupled components — where one change ripples through the rest of the codebase.</p><h4>1. ADP — Acyclic Dependencies Principle</h4><p>The dependency graph of components should never contain cycles. Components should not circularly depend on each other. The main problem with cyclic build is that it will make it a nightmare for developers, particularly known as <strong><em>Morning After Syndrome[2].</em></strong></p><blockquote>Eg: Suppose Component <strong>A</strong> (<strong>TenantPortal</strong>) depends on Component <strong>B</strong> (<strong>BillingService</strong>), which depends on Component <strong>C</strong> (<strong>InvoiceFormatter</strong>). If Component C ends up depending on Component A, it creates a <strong>cyclic dependency</strong>. This can cause build issues, test complications and opaque failure chains during runtime.</blockquote><p><strong>📌 Best Practice</strong>:</p><p>Organize components as a <strong>Directed Acyclic Graph (DAG)</strong>, where data flows one way and no component loops back.</p><h4>🕸️ What Is a Directed Acyclic Graph (DAG)?</h4><p>A <strong>DAG</strong> is a structure where components (nodes) depend on each other in a <strong>one-way</strong>, <strong>non-circular</strong> manner[3].</p><p><strong><em>Why it matters</em></strong></p><ul><li><em>Prevents </em><strong><em>circular dependencies</em></strong><em>.</em></li><li><em>Keeps architecture </em><strong><em>clean, testable, and scalable.</em></strong></li></ul><p><strong><em>How to Enforce DAGs in Practice</em></strong></p><ul><li><em>Architectural Layering</em></li><li><em>Use Dependency Rules in Tooling</em> (<strong>JavaScript/TypeScript</strong>: Tools like <a href="https://github.com/pahen/madge">Madge</a> or <a href="https://github.com/sverweij/dependency-cruiser">Depcruise</a> can visualize and detect circular imports, <strong>Monorepos</strong> (e.g., Nx or Turbo): Define dependency constraints in workspace.json.)</li><li><em>Use Dependency Injection &amp; Interfaces</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSnUGoPQhqgb__vQz0cKPg.jpeg" /><figcaption>DAG</figcaption></figure><h4>2. SDP — Stable Dependencies Principle</h4><p>A component should depend on more stable components, not less stable ones[3]. Depends on modules that are less likely to change. If the least stable component were at the bottom, it would force frequent changes across the stack. Stability at the base supports a reliable foundation.</p><blockquote>Eg: The component hierarchy should look like this:</blockquote><blockquote><strong>DomainLogic</strong> is the most stable (e.g., handles Data models).<br><strong>BusinessLogic</strong> depends on it but changes more often.<br><strong>UserInterface</strong> is the least stable and changes frequently.</blockquote><h4>🧱 Stable vs. Unstable Components</h4><p>In architecture, <strong>stability</strong> doesn’t mean “never changes” — it means <strong>how many other components depend on it[4]</strong>.</p><ul><li>A <strong>stable component</strong> has <strong>many dependents</strong>. Changing it is risky because it can break a lot.</li><li>An <strong>unstable component</strong> has <strong>few or no dependents</strong>, so it can change more freely.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*fhc0vyn70AFvmwwsTCGPHQ.png" /><figcaption>Stable vs Unstable components</figcaption></figure><blockquote>Eg: In a property management system:<br> <strong>EntityService</strong> is <strong>stable</strong> — many modules (e.g. LeaseService, TenantService) depend on it.<br> <strong>PromoBannerService</strong> is <strong>unstable</strong> — used only by the TenantPortal, so it’s easy to change or even rewrite.</blockquote><h4>3. SAP — Stable Abstractions Principle</h4><p>The more stable a component is, the more it should consist of abstract classes or interfaces[2]. Stable components should rely on abstractions (interfaces), not concrete classes, to allow flexibility. The more important and stable a component is, the more it should use interfaces instead of hard-coded classes.</p><p>This makes it easier to update or swap parts without breaking other things.</p><blockquote><strong>Eg</strong>: A shared PaymentGateway component used across your system should not lock you into one payment provider (e.g., Stripe). Instead, define:</blockquote><pre>interface IPaymentProcessor {<br>  process(amount: number): Promise&lt;boolean&gt;;<br>}</pre><blockquote>Then create separate implementations:</blockquote><pre>class StripeProcessor implements IPaymentProcessor { ... }<br>class PayPalProcessor implements IPaymentProcessor { ... }</pre><blockquote>This allows the core component to remain <strong>stable and extendable</strong>, even if individual payment integrations evolve.</blockquote><h4>🎯 Bringing It All Together</h4><ul><li><strong><em>ADP</em></strong><em> ensures that your components aren’t tangled in dependency loops.</em></li><li><strong><em>SDP</em></strong><em> helps you anchor your architecture in stable, low-volatility modules.</em></li><li><strong><em>SAP</em></strong><em> guarantees that your stable foundations remain open to extension, not just modification.</em></li></ul><p>Together, these principles <strong>protect your architecture from accidental complexity</strong>, reduce long-term maintenance costs, and foster cleaner, more modular designs.</p><p>Okay, I get it — this part feels a bit abstract and maybe even overly abstract. And you’re right, it is. But hear me out.</p><blockquote>The goal here isn’t to treat these principles like gospel or obsess over formulas. Instead, it’s to <strong>equip yourself with a mental model</strong> you can fall back on when making real-world architectural decisions. Think of it as a gut check, not a checklist.</blockquote><p>If you’re like me and you care deeply about building loosely coupled, well-structured systems, you’ll appreciate how <em>Robert C. Martin (Uncle Bob)</em> took a stab at <strong>quantifying architecture</strong> in <em>Clean Architecture[2]</em>. He introduced two metrics: <strong>Instability (I)</strong> and <strong>Abstractness (A)</strong>, which together define a component’s position on what he calls the <strong>“Main Sequence”</strong> — the sweet spot between being flexible and being dependable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*2cejpP9WEMkzSPzbHRtWng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Wqk6CoudyN47CCbYBv_xcA.png" /><figcaption>Formulas for calculating <strong>Instability (I)</strong> and <strong>Abstractness (A)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*AoFzyLEUKtGN7UiIZEg5kA.png" /><figcaption>Main sequence Graph</figcaption></figure><p>In real-world architecture:</p><ul><li><strong>Stable components</strong> should expose <strong>interfaces</strong>, not implementations[3].</li><li><strong>Unstable components</strong> (like UI layers) can afford to be concrete and flexible[3].</li></ul><p>This model <strong>quantifies what we intuitively feel</strong>: some parts of the system are “too risky to touch,” and others are “over-abstracted.” These metrics help architects validate those instincts.</p><p>Now that we’ve explored class structure through <strong>SOLID</strong> and component organization through <strong>cohesion and coupling principles</strong>, let’s take a step back and look at the <strong>big picture</strong> — how all of this plays out across layers and boundaries. This part isn’t about syntax or code. It’s about <strong>how we think</strong> about software when it gets real: growing teams, evolving domains, and multiple services trying to stay out of each other’s way.</p><h3>🧱 Practical Boundaries and Layering</h3><h4>🔲 Domain Boundaries</h4><p>Your domain logic — the core of what your application <em>does</em> — should never be entangled with details like how it’s stored in a database or shown on a screen.</p><blockquote>If you’re writing a <strong>LeaseRulesEngine</strong>, it should live in its own space, untouched by REST APIs, MongoDB schemas, or UI form logic. Let it breathe.</blockquote><p><strong>Why it matters </strong>→ This isolation makes your domain portable, testable, and resilient to changes in tech stacks or delivery mechanisms.</p><h4>🌍 Context Boundaries</h4><p>In the real world, systems often manage multiple domains. Each of those deserves its own space — or <strong>bounded context</strong>.</p><blockquote><strong>TenantManagement</strong> deals with accounts, access, and profiles.<br><strong>LeaseManagement</strong> handles contracts, durations, pricing.</blockquote><p>They both touch “tenants”, but <strong>they evolve for different reasons</strong>, and mixing them leads to a mess no one wants to debug during an incident.</p><h4><em>Pro tip: Don’t let your folder structure fool you. Just because it lives in src/modules doesn’t mean it’s truly independent.</em></h4><h4>🧭 Layering</h4><p>Classic, but powerful when done right. Think in layers like:</p><p>Each layer:</p><ul><li>Should depend only on the one below it</li><li>Should expose only what’s necessary above</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn97fPQI0iH-hGpaA-EEVg.png" /><figcaption>Layers</figcaption></figure><p><strong>Example</strong>:</p><ul><li>UI layer calls RenewLeaseCommand</li><li>That command calls LeaseService</li><li>Which uses domain logic and calls a repository interface</li></ul><p>Perfect — now that we’ve explored <strong>practical layering and boundaries</strong>, it’s a natural transition to zoom out and look at <strong>how components and modules can be structured at a system-wide level</strong>.</p><h3>🏗️ Architectural Patterns for Structuring Systems</h3><p>Here’s how different <strong>software architectural patterns</strong> help us design modules, enforce boundaries, and manage responsibilities across systems — not just within them. Each architectural pattern brings a different strategy for how we organize software components — based on team structure, scalability needs, coupling tolerance, or evolution speed. But I am not gonna dive deep into each of these as you already are aware of these as software engineers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10lEO7U1Ip3aq1yeKVfpFQ.png" /><figcaption>More frequently used system level software architecture modules</figcaption></figure><h4>1. Layered Architecture</h4><p><em>Classic, predictable, and still highly relevant</em></p><p>This is the most well-known approach — split your system into layers where each one has a clear responsibility.</p><blockquote><strong>Example</strong>: <br>Presentation Layer: React UI for tenants and admins<br>Business Layer: LeaseService, TenantManager<br>Persistence Layer: Repositories and data mappers<br>Database Layer: PostgreSQL or Mongo</blockquote><p><strong><em>✅ Great for monoliths, MVPs, and when teams are small</em></strong></p><p><strong><em>⚠️ Can become rigid and hard to scale horizontally if not modularized well</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EpGBJ3i301iuW0x_qZqcQ.png" /><figcaption>A basic example of a Layered Architecture, commonly seen in smaller Node.js or Express-based applications</figcaption></figure><h4>2. Microservice Architecture</h4><p><em>Decompose by business capability, scale independently</em></p><p>Each <strong>microservice</strong> is a bounded context, owning its own data and behaviour.</p><blockquote><strong>Example</strong>:<br>- TenantService, LeaseService, PaymentService, MaintenanceService each run independently.<br>- Communicate via HTTP or messaging.<br>- Each one has its own DB (PostgreSQL, Redis, etc.)</blockquote><p><strong><em>✅ Enables team autonomy, independent scaling</em></strong></p><p><strong><em>⚠️ Higher operational complexity — distributed systems are hard</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIzj0vXT411Mgs5UxmKrow.png" /><figcaption>Microservice Architecture codebase in TypeScript, where each service is an independently deployable unit with its own isolated structure</figcaption></figure><h4>3. Event-Driven Architecture</h4><p><em>Loose coupling through pub/sub or event buses</em></p><p>Instead of services calling each other directly, they <strong>react to events</strong>.</p><blockquote><strong>Example</strong>:<br>LeaseService emits LeaseRenewed → InvoiceService listens and generates an invoice → NotificationService sends a renewal confirmation</blockquote><p><strong><em>✅ Decouples systems, improves flexibility</em></strong></p><p><strong><em>⚠️ Debugging and tracing flow becomes more complex without observability tools</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*kdPPsSV_1uGOnE58Gk7xAw.png" /><figcaption>An example of a <strong>basic Event-Driven Architecture (EDA)</strong> codebase layout</figcaption></figure><h4>4. Client-Server Architecture</h4><p><em>Old but gold — the foundation of web systems</em></p><p>Clients (web/mobile apps) communicate with a server over a network.</p><blockquote><strong>Example</strong>:<br>React tenant dashboard (client) talks to your backend Node.js API (server)<br>Server handles requests, runs domain logic, and returns JSON responses</blockquote><p><strong><em>✅ Simple, universal</em></strong></p><p><strong><em>⚠️ The backend can become a bottleneck if not modularized well</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*wGsW6RVK12Iglh43ja7NIA.png" /><figcaption>A simple <strong>Client-Server Architecture</strong> codebase structure</figcaption></figure><h4>5. Plugin-Based Architecture</h4><p><em>Core logic surrounded by pluggable features or integrations</em></p><p>You have a central system that loads plugins dynamically.</p><blockquote><strong>Example</strong>:<br>Core PropertyEngine<br>Plugins: RentCalc, GeoTaxCalc, PromoBannerRules</blockquote><p><strong><em>✅ Amazing for extensibility and modularization</em></strong></p><p><strong><em>⚠️ Needs clear contracts and isolation boundaries to avoid spaghetti plugins</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*I_lGFM4mq5JoMWH7JwfNIQ.png" /><figcaption>clean and minimal <strong>Plugin-Based Architecture</strong> codebase structure</figcaption></figure><h4>6. Hexagonal Architecture (Ports &amp; Adapters)</h4><p><em>Also known as Clean or Onion Architecture</em></p><p>Core business logic (the “inside”) is isolated from delivery (UI, APIs) and infrastructure (DB, filesystems).</p><blockquote><strong>Example</strong>:<br>Core: LeaseRenewal, RateAdjuster<br>Ports: RenewLeaseCommand, PaymentProcessor<br>Adapters: Implement interfaces using REST APIs, Stripe, PostgreSQL</blockquote><p><strong><em>✅ Best for long-term maintainability and testability</em></strong></p><p><strong><em>⚠️ Initial learning curve and boilerplate might feel overkill for small apps</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*7hCfDSGcPNgYEHEqgTorrg.png" /><figcaption>A clean folder structure representing a <strong>Hexagonal Architecture (a.k.a. Ports and Adapters / Clean Architecture)</strong></figcaption></figure><h3>✅Conclusion: Structure Is Strategy</h3><p>In software, structure isn’t just about code hygiene — it’s a strategic asset. Whether you’re shaping a class, building a module, or stitching systems together, the decisions you make about boundaries, responsibilities, and dependencies ripple across your team, your product, and your future roadmap.</p><p>Through this article, we’ve walked through the foundations of <strong>SOLID</strong>, the dynamics of <strong>component cohesion and coupling</strong>, the rigour of <strong>instability and abstraction</strong>, and the practical realities of layering, modularization, and system-wide architecture.</p><p>We’ve seen how poor structure leads to fragility and frustration, while thoughtful design supports innovation, stability, and growth. Most importantly, we’ve shown that architecture isn’t something that happens at the “end” of design — it <strong>emerges</strong> from your codebase, from your components, and from your boundaries, every day.</p><p>If there’s one thing I’ve learned, it’s this:</p><blockquote><strong><em>Good structure doesn’t slow you down — it’s what lets you move fast and stay fast.</em></strong></blockquote><p>In the next article, we’ll explore how teams and services coordinate — covering communication models, Conway’s Law, and patterns like orchestration vs. choreography. Because clean code alone isn’t enough — <strong>architecture only scales when people and systems align. Ciao!</strong></p><h3>📚 References</h3><ol><li>Srinath Perera, <em>Software Architecture and Decision-Making: Leveraging Leadership, Technology, and Product Management to Build Great Products</em>, 2023.</li><li>Robert C. Martin, <em>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</em>, Prentice Hall, 2017.</li><li>Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship, Prentice Hall, 2008.</li><li>Mark Richards and Neal Ford, <em>Fundamentals of software architecture: an engineering approach, 2020</em></li><li>Gene Kim, Kevin Behr, and George Spafford, <em>The Phoenix Project: A Novel About IT, DevOps, and Helping Your Business Win</em>, IT Revolution Press, 2013.</li><li><a href="https://bytebytego.com/guides/6-software-architectural-patterns-you-must-know/">https://bytebytego.com/guides/6-software-architectural-patterns-you-must-know/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b66b8728df26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Software Architecture and System Performance]]></title>
            <link>https://cudakara.medium.com/software-architecture-and-system-performance-a9889624b727?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9889624b727</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-optimisation]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-performance]]></category>
            <category><![CDATA[system-performance]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Thu, 29 May 2025 19:06:53 GMT</pubDate>
            <atom:updated>2025-05-29T19:06:53.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntVrMVDYbRXQdY9gGS8alQ.png" /></figure><blockquote><em>Part 2 of the “Understanding Software Architecture” Series</em></blockquote><p>In the first part of this series, I walked through how I approach software architecture using a principle-first, question-driven mindset. This time, I want to go deeper into one of the most critical — and often misunderstood — facets of architecture: <strong>system performance</strong>.</p><h3>👋 Introduction</h3><p>When we talk about system performance, we usually think of metrics, profiling tools, or tuning configurations. But long before any of that, performance starts with <strong>software design and architecture</strong> — how we shape the system to behave predictably under load, avoid bottlenecks, and use resources efficiently.</p><p>Over time, I’ve found that <strong>mental models[1]</strong> are incredibly helpful for reasoning about performance from the very beginning. These models don’t require code — they give us a way to think about how systems behave under different conditions[3], what the trade-offs are, and where things might break.</p><p>In this article, I’ll walk through several of the models I use regularly, explaining how they influence my design choices. To make it more relatable, I’ll use examples from a property management system I’ve worked on — especially the parts that handle tenant payments through direct debit flows.</p><h3>🔧 Optimization Techniques That Actually Work</h3><p>When it comes to system performance, I’ve learned that optimization[1][2] isn’t about making everything faster — it’s about <strong>doing the right work, at the right time, in the most efficient way</strong>. It’s about reducing waste, avoiding unnecessary effort, and improving responsiveness without over-engineering.</p><p>Below are the core techniques experts and I (following in their footsteps) rely on — applied through real examples from a property management system that handles direct debit transactions.</p><h3>1. Optimize Individual Tasks</h3><p>Before scaling or introducing threads, start by making each task lean and purposeful.</p><p>🔍 <strong>Example</strong>:</p><p>Invoice generation was sluggish due to redundant DB joins and over-fetched data. We cleaned up the DB, added targeted indexes, and memoized config lookups — cutting execution time in half without changing infrastructure.</p><h3>2. Optimize Memory Use</h3><p>Memory pressure can create latency spikes, crashes, or slow GC cycles.</p><p><strong>Techniques:</strong></p><ul><li><strong>Use Bloom filters to skip expensive reads</strong>. — Eg: In the direct debit module, before checking if a tenant had opted into mandate-based payments, we used to query the database for each request. This was slow and hit the DB unnecessarily. We introduced a Bloom filter preloaded with opted-in tenant IDs. If the tenant ID wasn’t in the filter, we skipped the DB call altogether.</li><li><strong>Cache preferences/configs only when they change</strong>. — Eg: Every time we generated an invoice, we fetched locale, currency, and notification settings from the database — even though tenants rarely updated them. We moved to an event-based cache. When a tenant updates their profile, we invalidate and refresh the cache. Otherwise, we serve config from Redis.</li><li><strong>Apply buffering for write-heavy processes.</strong> — Eg: Our audit logs were written to disk every time a direct debit was processed — causing file system thrashing and slowdowns under load. We introduced a buffer that batched log entries and flushed them every few seconds in a separate async process.</li></ul><pre>let buffer: string[] = [];<br><br>function audit(entry: string) {<br>  buffer.push(entry);<br>  if (buffer.length &gt;= 50) flushBuffer();<br>}<br><br>async function flushBuffer() {<br>  const toWrite = buffer.splice(0, buffer.length);<br>  await writeToDisk(toWrite.join(&#39;\n&#39;));<br>}</pre><h3>3. Maximize CPU Utilization</h3><p>Running more threads isn’t always the answer — using the CPU wisely is.</p><p><strong>Techniques:</strong></p><ul><li><strong>Use shared job queues </strong>(e.g., SQS, BullMQ) so CPU workers don’t sit idle.</li><li>Apply <strong>task stealing</strong> to avoid starvation across pools.</li><li><strong>Minimize locks and shared memory</strong> to prevent contention.</li></ul><h3>4. IO Optimization</h3><p>Disk, DB, and network I/O are often the bottlenecks — not your app logic.</p><p>🔍 <strong>Example</strong>:</p><p>We were querying payment histories for every tenant invoice rendered. Instead, we moved to an <strong>event-driven ledger</strong> system that cached the balance after each transaction.</p><p><strong>Tactics:</strong></p><ul><li>Avoid unnecessary disk/network calls.</li><li>Use <strong>append-only logging</strong> where possible.</li><li><strong>Batch writes</strong> instead of writing small chunks repeatedly. — Eg: Doing 100 small operations is usually worse than doing one large one. Instead of calling the bank API per tenant, we aggregated them into a single batch[4].</li></ul><pre>const payload = tenants.map(t =&gt; ({<br>  id: t.id,<br>  mandate: t.mandateRef,<br>  amount: t.nextInvoiceAmount<br>}));<br><br>await bankApi.processDirectDebits(payload);</pre><h3>5. Latency Optimization</h3><p>When users are waiting, milliseconds add up.</p><p>🔍 <strong>Example</strong>:</p><p>In the direct debit flow, we used to verify mandates and fetch configs during payment. Instead, we <strong>preloaded and cached</strong> that data ahead of time, cutting live processing time to under 100ms.</p><p><strong>Guidelines:</strong></p><ul><li><strong>Send early, receive late</strong> — proactively prepare and fetch data before it’s needed.</li><li>Split long chains into parallel or background operations.</li></ul><h3>7. Asynchronous Decomposition</h3><p>Everything doesn’t need to happen now. Separate fast user feedback from slow post-processing.</p><p>🔍 <strong>Example</strong>:</p><p>We moved PDF receipt generation and audit logging to background jobs triggered by events — returning the UI response instantly.</p><h3>8. Cache Tuning &amp; Shared State Awareness</h3><p>Symptoms like cache misses or shared memory contention often go unnoticed until the system hits scale.</p><p><strong>What we should watch for:</strong></p><ul><li><strong>Too many cache misses? Revisit eviction policies or key design. </strong>— Eg: In the tenant dashboard, we cached profile data using long TTLs, but as new tenants were onboarded, older ones were evicted too quickly — leading to frequent cache misses for active users. We moved from a simple LRU (Least Recently Used) cache to <strong>LFU (Least Frequently Used)</strong> and updated cache keys to use compact, hashable formats like t<em>enant:{id}: settings</em> instead of verbose strings[6].</li><li><strong>Shared variables? Reduce or isolate them using scoped processing or queues</strong>. -Eg: During bulk payment processing, multiple threads wrote status updates to the same MongoDB document (payment_status_log), causing lock contention and inconsistent data. We split logs by tenant ID and processed them using a <strong>dedicated queue per tenant</strong>, eliminating concurrent writes to shared records.</li><li><strong>Not enough memory? Offload large datasets and preload only essentials.</strong> — Eg For our background job for generating financial summaries loaded full transaction histories into memory. As the system grew, memory pressure caused container OOM (Out Of Memory) crashes. We moved to a <strong>streaming model</strong>: fetched transactions in chunks, computed partial aggregates, and wrote intermediate results to disk or S3. This cut memory usage by over 80%.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UItlHh00bidZ5S8sOBuYxQ.jpeg" /><figcaption>Caching Stratergies</figcaption></figure><p>So far, we’ve seen how these optimization techniques can significantly improve system performance. But applying them effectively requires more than just tactical fixes — it demands a solid understanding of <strong>how performance works</strong>, what <strong>trade-offs</strong> are involved, and how these choices fit into the broader system architecture.</p><p>To build that kind of understanding, I rely heavily on <strong>mental models</strong> — concepts that help me reason about performance in a structured way. Over time, I’ve found that the best insights come from foundational books and real-world architectural patterns that frame performance as a system-wide concern, not just a backend one.</p><h3>Mental Models to Understand System Performance (with Simple Examples)</h3><h4>1. Kernel vs User Mode Switching</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eECY8rg6Rrhq0DDTllTPHQ.png" /></figure><p>Every time your application makes a system call — like writing to disk or accessing a file [1]— it switches from user mode to kernel mode. These context switches are expensive and add up quickly.</p><p>🔍 <strong>Example</strong>: — If you’re writing logs to disk on every direct debit transaction, you’re paying the price of a syscall each time.</p><p>✅ <strong>Optimization</strong>: — Buffer logs entries in memory and writes them in batches.</p><h4>2. Latency Cost Hierarchy</h4><p>Not all operations are equal. Some are lightning-fast (like reading from cache), while others (like remote API calls) are significantly slower[5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFVeGS4Wux4mbKD73g6yAg.jpeg" /></figure><p>🔍 <strong>Example</strong>: — Fetching tenant configs from Redis takes microseconds. Hitting the DB or external config service can take hundreds of milliseconds.</p><p>✅ <strong>Optimization</strong>: — Always prioritize in-memory access for frequently-read values.</p><h4>3. Amdahl’s Law</h4><p>In computer architecture, <strong>Amdahl’s law</strong> (or <strong>Amdahl’s argument</strong>) is a formula that shows how much faster a task can be completed when more resources are added to the system. So, even with unlimited threads, your performance is limited by the portion of the task that’s sequential.[3]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*OR42a_w0XA2a3O7Kqz3u-A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUbDwK_7BbKPOrsefyUBRg.png" /><figcaption>Amdhal’s law Formula and Distribution</figcaption></figure><p>🔍 <strong>Example</strong>: — In our bulk payment flow, if the direct debit mandate check is synchronous and takes 1 second, you’ll hit a hard performance ceiling regardless of how many other tasks are parallelized.</p><p>✅ <strong>Optimization</strong>: — Break serial flows into smaller units or use async APIs.</p><h4>4. Context Switching Cost</h4><p>More threads don’t always mean more performance. The CPU needs time to switch between threads — each switch costs cache locality and processing time[1].</p><p>🔍 <strong>Example</strong>: — We had 100+ threads running invoice generation jobs. The system spent more time switching than doing actual work.</p><p>✅ <strong>Optimization</strong>: — Use a thread pool size to match your CPU cores, and offload non-urgent tasks.</p><h4>5. GUNTHER’s Universal Scalability Law (USL)</h4><p>USL builds on Amdahl’s Law by accounting for <strong>contention</strong> (resources being fought over) and <strong>coherency</strong> (keeping shared state consistent)[8]. So As the services scale up, the coordination cost between nodes eventually exceeds the scaling benefit due to costs imposed by both contention and coherency delay[8].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oFfpBzBSiDsNdlj-2exog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*2PCWMmfJAwGQOKT1NIsykQ.png" /><figcaption>Universal Scalability Law formula and Graph</figcaption></figure><p>🔍 <strong>Example</strong>: — Multiple services writing to the same billing document caused lock contention and write conflicts.</p><p>✅ <strong>Optimization</strong>:- Isolate shared state using queues or shards.</p><h4>6. Latency vs Utilization</h4><p>As system utilization increases, latency rises exponentially — especially beyond 70–80%. In any system, <strong>utilization</strong> measures how “busy” the system is, typically as a percentage of its total capacity. When utilization is low, requests can be handled immediately. But as it rises, requests begin to <strong>queue up</strong>, waiting their turn. This wait time adds latency. And the closer you get to 100% utilization, the longer the queues — and the slower everything gets[3].</p><p>This isn’t a linear slowdown. It’s <strong>exponential</strong>.</p><p>🔍 <strong>Example</strong>: — When the invoice generator ran on a 90% utilized node, latency for all tenants spiked, even on simple reads.</p><p>This phenomenon is modelled by <strong>Queuing Theory</strong>, particularly the <strong>M/M/1 queue</strong> model. The rule of thumb is:</p><blockquote><em>📈 As system utilization (ρ) approaches 1 (or 100%), average wait time → ∞.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*xftQ08H9AWWow7MjqQERNQ.png" /></figure><p>✅ <strong>Optimization</strong>: — Run critical workflows on isolated, lightly loaded nodes.</p><h4>7. Throughput &amp; the MUU(Maximal Useful Utilization) Model</h4><p>In simple terms, <strong>throughput</strong> is how much useful work your system can complete per unit of time[1]. This model suggests you hit maximum throughput when:</p><ul><li>Overhead is minimized</li><li>Work is predictable</li><li>The slowest resource is used efficiently</li></ul><pre>High Throughput = Lean tasks + Low overhead + Saturated bottleneck</pre><p>🔍 <strong>Example</strong>: — When the direct debit handler also generated PDFs and sent receipts, throughput dropped. Those were non-critical tasks.</p><p>✅ <strong>Optimization</strong>: — Move auxiliary work to background queues.</p><h3>8. Trade-offs (Last but not least)</h3><p>Every performance win comes with a trade-off — whether it’s data freshness, consistency, or resource overhead[3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfGQwzrFQ803BqlLmf1IgA.png" /></figure><p>🔍 <strong>Example</strong>: — Caching tenant settings reduced DB hits, but introduced a delay in reflecting updated values.</p><p>✅ <strong>Optimization</strong>: — Use short-lived or event-driven cache invalidation strategies.</p><h3>Wrapping Up: Performance is an Architectural Mindset</h3><p>System performance isn’t just about scaling infrastructure or tuning configs — it’s about <strong>thinking architecturally from the start</strong>. Throughout this article, we explored how real-world optimization techniques and mental models help shape reliable, efficient systems, even under pressure.</p><p>From minimizing waste in task execution to understanding the limits imposed by coordination and shared state, we’ve seen how small design decisions can have a massive downstream impact. Whether it’s buffering logs, batching API calls, or rethinking data access patterns, these strategies helped me deliver faster and more predictable user experiences — especially in systems like property management platforms with critical payment workflows.</p><p>But performance is just one piece of the puzzle.</p><p>In the <strong>next part of this series</strong>, we’ll shift focus to another foundational element of good architecture:</p><p>🔄 <strong>Component Structuring</strong> — how we break down systems into modules and services that are coherent, maintainable, and aligned with team ownership and change velocity.</p><p>Until then, remember:</p><blockquote><em>Great performance is not just built — it’s </em><strong><em>designed, questioned, and refined</em></strong><em>.</em></blockquote><h3>📚 References</h3><ol><li>Srinath Perera, <em>Software Architecture and Decision-Making: Leveraging Leadership, Technology, and Product Management to Build Great Products</em>, 2023.</li><li>Robert C. Martin, <em>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</em>, Prentice Hall, 2017.</li><li>Mark Richards and Neal Ford, <em>Fundamentals of software architecture: an engineering approach, 2020</em></li><li><a href="https://bytebytego.com/guides/top-5-common-ways-to-improve-api-performance/">https://bytebytego.com/guides/top-5-common-ways-to-improve-api-performance/</a></li><li><a href="https://bytebytego.com/guides/which-latency-numbers-should-you-know/">https://bytebytego.com/guides/which-latency-numbers-should-you-know/</a></li><li><a href="https://bytebytego.com/guides/what-are-the-top-caching-strategies/">https://bytebytego.com/guides/what-are-the-top-caching-strategies/</a></li><li><a href="https://bytebytego.com/guides/most-popular-cache-eviction/">https://bytebytego.com/guides/most-popular-cache-eviction/</a></li><li><a href="http://thinkmicroservices.com/blog/2019/laws-of-scalability.html#:~:text=GUNTHER&#39;s%20Universal%20Scalability%20law&amp;text=The%20Universal%20Scalability%20Law%20is,of%20contention%20in%20the%20system">http://thinkmicroservices.com/blog/2019/laws-of-scalability.html#:~:text=GUNTHER&#39;s%20Universal%20Scalability%20law&amp;text=The%20Universal%20Scalability%20Law%20is,of%20contention%20in%20the%20system</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9889624b727" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding and Designing Software Architecture Through Mental Models: A Pragmatic Guide for…]]></title>
            <link>https://cudakara.medium.com/understanding-and-designing-software-architecture-through-mental-models-a-pragmatic-guide-for-4cc2942c202b?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cc2942c202b</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Thu, 29 May 2025 18:36:53 GMT</pubDate>
            <atom:updated>2025-05-29T18:36:53.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rvnp3b7MPvlyvY8BkN3fQ.png" /></figure><h3>🧠 Understanding and Designing Software Architecture Through Mental Models: A Pragmatic Guide for Software Engineers</h3><blockquote><em>“All architecture is design, but not all design is architecture.”</em></blockquote><blockquote><em>— Ralph Johnson</em></blockquote><p>Software architecture is more than just diagrams and documentation as we all know already. It’s the <strong>thought process</strong> behind how systems scale, adapt and endure. It goes deep into a single code line we write as software developers. For anyone leading product development or working as a software engineer, having a clear mental framework to navigate architectural decisions is essential.</p><p>In this article, we explore the fundamentals of software architecture and how to use <strong>mental models</strong> to improve system performance, reliability, and maintainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ji0TIImBfqWQeRIEfjYG3Q.png" /></figure><h3>🧩 What Is Software Architecture?</h3><p>In my view, <strong>software architecture is not just about drawing diagrams or writing documentation</strong> — it’s about building a mental model for how a system should be structured and how it should be performed with less maintainability. It’s the framework I fall back on when deciding how things should be structured and how they should interact with each other.</p><p>At its core, architecture is about two things:</p><ul><li><strong>Structural definition</strong> — deciding what components we need (like services, code structure, components, APIs, databases, queues).</li><li><strong>Behavioural coordination</strong> — defining how these components and implementation details communicate and work together.</li></ul><p>Let’s take <strong>Netflix</strong> as an example. Structurally, they broke down their monolith into hundreds of microservices — each responsible for a specific task, such as recommendations, user profiles, or video encoding. Behaviorally, these services interact over REST or gRPC with strict API contracts and caching layers like Redis or CDN edge nodes to reduce latency[2][3]. (Of course, I do not know the exact stack they are using but you get the principal). Or consider <strong>Uber</strong>. Their dispatch system involves real-time messaging, location tracking, and pricing calculations, often built using applications communicating via message brokers (like Kafka)[4]. The structural components include services for ride-matching, payments, driver location services, etc., and they all must coordinate in real-time without breaking under heavy load.</p><p>But here’s the catch — <strong>architecture is never a one-and-done job</strong>. It evolves as the product scales, the team grows, and the users change. For instance, when I worked on a TypeScript-based platform handling multi-tenant data ingestion, our initial single-node setup worked well. But as traffic grew and new use cases came in, we had to move to event-driven architecture using AWS Lambda and SQS. That wasn’t just a technical shift — it was an architectural evolution driven by business scale.</p><p>What I’ve come to learn[1] — and firmly believe — is that software architecture is as much about <strong>navigating uncertainty</strong> as it is about making <strong>well-informed decisions</strong>. Some of the biggest uncertainties we as software engineers regularly encounter include[1]:</p><ul><li>Having only a <strong>partial understanding of what users truly want</strong> — until we see how they interact with what we’ve built.</li><li>Watching <strong>requirements shift</strong>, especially in agile environments where business goals change rapidly.</li><li>Struggling with <strong>limited observability into performance</strong>, especially when debugging intermittent slowdowns in a production API that behaves perfectly in staging.</li><li>Having to <strong>rely on guesswork </strong>due to limited knowledge of a system (especially with legacy systems)</li></ul><p>So for me, being an architect/engineer means continuously balancing what I know with what I assume (mind that this is not as easy as it sounds)— and creating structures flexible enough to absorb surprises and changes. It’s less about predicting the future and more about designing systems that are <em>ready for change</em>.</p><h3>✅ 3 Best Practices Every Architect Should Follow</h3><p><strong>1.Delay irreversible decisions until the last responsible moment. →<br></strong>In software development, it’s prudent to postpone binding decisions until sufficient information is available. For instance, when developing a web application, you might initially use a simple in-memory data store during the prototyping phase. As requirements become clearer, you can then decide on a more permanent database solution, such as PostgreSQL or MongoDB, based on the specific needs identified.</p><blockquote>In <em>Clean Architecture</em> by Robert C. Martin, it’s emphasized that architects should design systems to defer decisions about frameworks, databases, or UI technologies. This approach allows for flexibility and adaptability as more information becomes available during development.</blockquote><p><strong>2. Design for clarity and change — complexity is the enemy. → <br></strong>Aim for simplicity in your architectural designs. A straightforward, modular structure is easier to understand, maintain, and scale. For example, structuring your application into distinct layers — such as presentation, business logic, and data access — can help isolate concerns and facilitate easier updates and debugging.</p><blockquote>Mark Richards and Neal Ford, in <em>Fundamentals of Software Architecture</em>, advocate for simplicity and clarity in design. They stress that a clear architecture is easier to understand, maintain, and evolve.</blockquote><p><strong>3. Say no to unnecessary features to preserve simplicity. →<br></strong>Focus on delivering features that provide real value to users. Adding superfluous functionalities can complicate the system and introduce unnecessary maintenance overhead. For instance, before integrating a complex reporting dashboard, assess whether users need it immediately or if a simpler solution, like exporting data to CSV, would suffice in the short term.</p><blockquote>Srinath Perera, in <em>Software Architecture and Decision-Making</em>, discusses the importance of focusing on features that deliver the most value. By avoiding unnecessary features, architects can maintain a lean and efficient system.</blockquote><p>From my experience (which is not that much), and from what I’ve learned through reading different books, I really like the way Dr. Srinath Perera approaches architecture in his book <em>Software Architecture and Decision-Making</em>. He suggests that before jumping into designing a system, we should ask a few important questions.</p><h3>🤔 Ask These 5 Questions Before Designing</h3><ol><li><strong>What’s the target time to market? — — — — — — — — — — — — — — — — — — —</strong>Understanding the desired launch timeline helps in making trade-offs between speed and completeness. If a quick release is essential, prioritize core functionalities and plan to add enhancements in subsequent iterations. Mind that architecture and design are all about tradeoffs (so basically you cannot have it all)</li><li><strong>What’s the team’s skill and ownership maturity? — — — — — — — — — — —</strong>Assess the team’s expertise and experience. If the team is more familiar with certain technologies or architectural patterns, leveraging those can lead to more efficient development and better outcomes. Remember that developers(liveware) are the most expensive resource in a software system.</li><li><strong>How performance-sensitive is the system? — — — — — — — — — — — — — —<br></strong>Determine if the application requires high performance or can tolerate some latency. For a real-time chat application, low latency is critical, whereas, for a batch processing system, performance demands might be less stringent.</li><li><strong>Will we get the chance to rewrite this? — — — — — — — — — — — — — — — —</strong>Consider the likelihood of revisiting and refactoring the system. If a rewrite is improbable, invest more in creating a robust and flexible architecture from the outset. Rewriting and refactoring are inevitable, so the realistic question is not why but when.</li><li><strong>What are the most complex areas of this product? — — — — — — — — — —</strong>Identify components that are inherently complex or carry the most risk. These areas may require more thorough design and testing to ensure reliability and maintainability. In summary, just take a ballpark understanding of unknown unknowns.</li></ol><p>These questions help us understand the situation better. Based on the answers, we can then decide what kind of architecture makes the most sense.</p><p>I find this approach useful in my own work because it keeps the design practical and focused on what actually matters. Once we have the answers to these questions we can simply follow a few principles when we design and architecture the system.</p><h3>📐 Principles That Drive Good Architecture</h3><ol><li><strong>User Journey First: Align architecture to the real-world flow of users.<br></strong>Design your system to support the user’s journey seamlessly. For example, in a property management system, the user journey might begin with a tenant registering their account, setting up payment preferences, and eventually viewing and paying invoices. Your architecture should reflect this flow. Rather than handling payment setup as a separate process, integrate it directly into the onboarding experience — allow tenants to select direct debit during registration to create a smooth and intuitive experience.</li><li><strong>Iterative Slicing: Design in vertical slices that add value.<br></strong>Implement features in end-to-end slices that deliver user value. For instance, instead of building all modules at once (invoicing, notifications, bank integration), start with a working vertical slice: a tenant can log in, view rent, and pay using direct debit. This small, functional piece delivers real value and allows quick feedback before expanding the system.</li><li><strong>Effort vs Value Ratio: Optimize for delivering high-impact, low-effort slices.<br></strong>Prioritize features that offer significant user benefits with minimal development effort. This approach ensures efficient use of resources and quicker delivery of valuable functionalities. Imagine integrating bank APIs for direct debit takes weeks, but generating a downloadable rent invoice takes a day. Deliver the invoice feature first—it’s quick to build and still gives users a win. Prioritize what creates the most value for the least effort.</li><li><strong>Risk Ownership: Make calls; don’t defer tough decisions.<br></strong>Take responsibility for critical architectural decisions. Avoid postponing choices that could impact the project’s success, and be prepared to justify and stand by your decisions. For instance, deciding whether to store tenants’ bank details or use a third-party payment provider is a critical architectural decision. Don’t postpone it. Assess the trade-offs (security, compliance, cost) and make a call early to avoid future rework.</li><li><strong>Slow Implementations of Deep Designs: Think deeply before building things that are hard to undo.<br></strong>For foundational components that are difficult to change later, invest time in thorough design and validation. For example, setting up your system’s recurring billing logic or mandate management for direct debits is not something you want to redo often. So take time to model this part well—cover edge cases like failed debits, mandate expirations, and partial payments before locking in your design.</li><li><strong>Eliminate Unknowns Early: Parallelize efforts and validate fast.<br></strong>Identify and address uncertainties early in the development process. Conduct experiments or prototypes to validate assumptions, reducing the risk of costly changes later. If you’re not sure whether the bank API supports instant mandate setup, test it early with a small proof of concept. Meanwhile, other team members can work on tenant profile screens or email templates. This way, you’re not blocked and reduce risk at the same time.</li><li><strong>Balance Cohesion vs Flexibility: Tightly coupled modules are easier to manage; loosely coupled ones are more reusable. <br></strong>Strive for a balance between cohesive modules that are easy to understand and manage, and loosely coupled components that offer flexibility and reusability. You might keep tenant management, invoicing, and payment processing in separate services. But if too loosely coupled, they may become hard to coordinate. Instead, aim for a healthy balance—like using event-driven communication (<em>e.g., invoice.generated → payment.requested</em>) while maintaining clear module boundaries.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keL-C910B6pORwS29lZcXA.png" /></figure><h3>🧱 Main Aspects of Software Architecture &amp; System Design</h3><p>In my experience, every solid architecture decision touches multiple aspects — not just code structure, but also how the system performs, scales, and supports real-world use. When great architects approach a system design, they don’t look at it in isolation. They consciously think about how components talk to each other, how the system handles errors, how secure and observable it is, and how the architecture supports a seamless user journey[6].</p><h4>1. Performance &amp; Efficiency</h4><p>How fast the system responds and how well it uses resources.</p><ul><li>Optimize for <strong>low latency</strong> and <strong>high throughput</strong>.</li><li>Apply mental models like <strong>context switching overhead</strong>, <strong>Amdahl’s Law</strong>, and <strong>cache locality</strong>.</li><li>Minimize I/O blocking and avoid premature optimization.</li></ul><h4>2. Coordination &amp; Communication</h4><p>How components interact with each other.</p><ul><li>Sync vs async communication (e.g., REST vs. events via SQS/Kafka).</li><li>Message coordination with orchestration and choreography patterns.</li><li>Well-defined <strong>API contracts</strong>.</li></ul><h4>3. Component Structuring</h4><p>How your system is broken down into modules, layers, or services.</p><ul><li>Ensure <strong>separation of concerns</strong> (e.g., user service vs. billing service).</li><li>Structure for <strong>modularity</strong>, maintainability, and readability.</li><li>Choose between monolith, modular monolith, or microservices based on context.</li></ul><h4>4. User Experience (UX) Integration</h4><p>How the architecture supports a seamless user journey.</p><ul><li>Align system behaviour with <strong>real user flows</strong>.</li><li>Ensure <strong>fast response times</strong> for critical interactions.</li><li>Should be intuitive to users.</li></ul><h4>5. Persistency &amp; State Management</h4><p>How and where data is stored.</p><ul><li>Choose appropriate storage types (SQL, NoSQL, in-memory).</li><li>Ensure <strong>consistency</strong>, <strong>durability</strong>, and <strong>failover recovery</strong>.</li><li>Use <strong>event sourcing</strong> or <strong>CQRS</strong> when helpful.</li></ul><h4>6. Security</h4><p>How the system protects against unauthorized access and attacks.</p><ul><li>Secure APIs with authentication (e.g., OAuth2, JWT).</li><li>Handle sensitive data with encryption (in transit + at rest).</li><li>Consider threat models like <strong>XSS, CSRF, injection, and replay attacks</strong>.</li></ul><h4>7. High Availability (HA) &amp; Scalability</h4><p>How resilient and extensible the system is.</p><ul><li>Use <strong>replication</strong>, <strong>load balancing</strong>, and <strong>auto-scaling</strong>.</li><li>Design stateless services to scale horizontally.</li><li>Introduce redundancy for fault tolerance.</li></ul><h4>8. Service Architecture</h4><p>How services are designed, exposed, and integrated.</p><ul><li>Pick the right style: REST, GraphQL, gRPC, or Event-Driven.</li><li>Define service boundaries based on <strong>business capabilities</strong>.</li><li>Handle versioning, backward compatibility, and SLA contracts.</li></ul><h4>9. Design Patterns &amp; Principles</h4><p>Applying reusable solutions to common problems.</p><ul><li>Patterns like <strong>Factory</strong>, <strong>Builder</strong>, <strong>Strategy</strong>, <strong>Observer</strong>, <strong>Adapter.</strong></li><li>Architectural styles like <strong>hexagonal architecture</strong>, <strong>onion architecture</strong>, and <strong>clean architecture</strong>.</li><li>Use principles like <strong>SOLID</strong>, <strong>DRY</strong>, and <strong>KISS</strong> to guide low-level design.</li></ul><h4>10. Error Handling &amp; Resilience</h4><p>How your system reacts to failures.</p><ul><li>Graceful degradation (e.g., fallback UI, cached responses).</li><li>Retry mechanisms with exponential backoff.</li><li>Centralized error logging and correlation IDs for tracing.</li></ul><h4>11. Observability &amp; Monitoring</h4><p>Understanding what your system is doing in production.</p><ul><li>Use tools like <strong>Prometheus</strong>, <strong>Grafana</strong>, <strong>Datadog</strong>, or <strong>AWS CloudWatch</strong>.</li><li>Implement <strong>structured logging</strong>, <strong>tracing (OpenTelemetry)</strong>, and <strong>alerting</strong>.</li><li>Track <strong>latency</strong>, <strong>error rates</strong>, <strong>CPU/memory usage</strong>, and <strong>business KPIs</strong>.</li></ul><p>Finally the most important and most overlooked aspect…</p><h4>12. Dev Experience with the System and Design</h4><p>Understanding the pain points of developers and trying to solve them with the approach to system design.</p><ul><li>Five Ideals of Working Software</li><li>Optimize for daily flow: Fast CI/CD feedback loops, reliable test coverage, and well-documented modules help developers stay productive and focused.</li></ul><h4>🏁 Conclusion</h4><p>Writing this has helped me reflect on how much architecture is not just about technology — but about making thoughtful decisions under uncertainty, grounded in context.</p><p>In this article, I focused on laying the groundwork: the core principles and aspects I believe every architect should think about before diving into design. These are the lenses I use in my day-to-day work to build systems that are not only functional, but also resilient, scalable, and a joy to work on.</p><p>In my next article, I’ll go deeper into <strong><em>System performance, and how to understand it using mental models </em></strong>— like Amdahl’s Law, the Universal Scalability Law, and the MUµ model.</p><p>If you’re interested in going beyond structure and starting to think like a performance-aware architect, stay tuned.</p><h3>📚 References</h3><ol><li>Srinath Perera, <em>Software Architecture and Decision-Making: Leveraging Leadership, Technology, and Product Management to Build Great Products</em>, 2023.</li><li><a href="https://bytebytego.com/guides/netflix-tech-stack-databases/">https://bytebytego.com/guides/netflix-tech-stack-databases/</a></li><li><a href="https://bytebytego.com/guides/netflixs-tech-stack/">https://bytebytego.com/guides/netflixs-tech-stack/</a></li><li><a href="https://bytebytego.com/guides/uber-tech-stack/">https://bytebytego.com/guides/uber-tech-stack/</a></li><li>Robert C. Martin, <em>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</em>, Prentice Hall, 2017.</li><li>Mark Richards and Neal Ford, <em>Fundamentals of software architecture: an engineering approach, 2020</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cc2942c202b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Pipeline and Architecture Basics]]></title>
            <link>https://cudakara.medium.com/data-pipeline-and-architecture-basics-06a6eaa867ad?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/06a6eaa867ad</guid>
            <category><![CDATA[data-workflow]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[pipeline-architecture]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 10:01:11 GMT</pubDate>
            <atom:updated>2024-07-01T20:49:24.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Pipeline Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsIejt685Bq-TurUXUjukw.jpeg" /></figure><h3>Introduction</h3><h4>What is a Data Pipeline?</h4><p>A data pipeline is <strong>a method where raw data is ingested from data sources, transformed, and then stored in a</strong> data lake or data warehouse for analysis.</p><p>In computing, a pipeline, also known as a data pipeline, is a set of data processing elements connected in series, where the output of one element is the input of the next. The elements of a pipeline are often executed in parallel or time-sliced fashion.</p><p><strong>Pipeline Types:</strong></p><ul><li>Batch Pipelines</li><li>Streaming Pipelines</li><li>Cloud-native Pipelines</li><li>On-prem data Pipelines</li></ul><h4>What is a data workflow?</h4><p>A data workflow is a series of steps or tasks that are performed on data in order to achieve a specific outcome or goal. These steps can include tasks such as data extraction, cleaning, transformation, analysis, and visualization.</p><h4>Data pipeline vs Data workflow?</h4><p>The terms “data workflow” and “data pipeline” are often used interchangeably in data engineering and data science, but they have distinct meanings and applications. Here’s a breakdown of the differences between the two:</p><p><strong>Data Workflow Key Characteristics:</strong></p><ol><li><strong>Sequential Tasks:</strong> Data workflows consist of a sequence of tasks that need to be executed in a particular order.</li><li><strong>Human Interaction:</strong> Often involves steps that require human decision-making or interaction, such as data validation, manual data correction, or interpretation of analysis results.</li><li><strong>Flexibility:</strong> Data workflows can be more flexible and adaptable to changes in the process or data requirements.</li><li><strong>Tools:</strong> Typically managed using workflow management tools like Apache Airflow, Luigi, or even spreadsheet software for simpler workflows.</li><li><strong>Scope:</strong> Broad and can encompass various stages of data handling, from raw data acquisition to the final reporting and visualization stages.</li></ol><p><strong>Example:</strong> A data workflow might include:</p><ol><li>Extracting data from a database.</li><li>Cleaning and preprocessing the data.</li><li>Running statistical analysis or machine learning models.</li><li>Creating visualizations.</li><li>Reporting results to stakeholders.</li></ol><p><strong>Data Pipeline Key Characteristics:</strong></p><ol><li><strong>Automation:</strong> Data pipelines are typically fully automated, requiring minimal human intervention once set up.</li><li><strong>Data Movement:</strong> Primarily concerned with the transportation and transformation of data between different systems, databases, or services.</li><li><strong>Reliability and Scalability:</strong> Designed to be robust, scalable, and able to handle large volumes of data with minimal latency.</li><li><strong>Tools:</strong> Implemented using specialized tools and platforms like Apache Kafka, Apache NiFi, AWS Data Pipeline, Google Dataflow, or custom ETL (Extract, Transform, Load) scripts.</li><li><strong>Scope:</strong> Narrower focuses on ensuring data is moved, transformed, and loaded efficiently and accurately between systems.</li></ol><p><strong>Example:</strong> A data pipeline might include:</p><ol><li>Extracting data from a web API.</li><li>Transforming the data format and structure.</li><li>Loading the transformed data into a data warehouse.</li><li>Continuously monitoring and maintaining data quality.</li></ol><h3>Main Components of Data Pipelines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y119jfRNJjXoqeUv2hAj9A.png" /></figure><h4>1. Data sources</h4><p>The first component of the modern data pipeline is where the data originates. Any system that generates data your business uses could be your data source, including:</p><ul><li>Analytics data (user behaviour data)</li><li>Transactional data (data from sales and product records)</li><li>3rd party data (data your company doesn’t collect directly but uses)</li></ul><h4>2. Data collection/ingestion</h4><p>The next component in the data pipeline is the ingestion layer responsible for bringing data into the data pipeline. This layer leverages data ingestion tools such as <a href="https://www.striim.com/">Striim</a> to connect to various data sources (internal and external) over a variety of protocols. For example, this layer can ingest batch (data at rest) and streaming (data in motion) data and deliver it to big data storage targets.</p><h4>3. Data processing</h4><p>The processing layer is in charge of transforming data into a consumable state through data validation, clean-up, normalization, transformation, and enrichment. Depending on the company’s specific architecture, ETL (Extract Transform Load) vs. ELT (Extract Load Transform), the data pipeline can do this processing component before or after data is stored in the data store.</p><p>In an ETL-based processing architecture, the data is extracted, transformed, and then loaded into the data stores; this is mainly used when the data storage is a data warehouse. In ELT-based architectures, data is first loaded into data lakes and then transformed into a consumable state for various business use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*oQ4hrf-ZSAn3c4khWEN8JA.png" /><figcaption>ETL vs ELT</figcaption></figure><h4>4. Data storage</h4><p>This component is responsible for providing durable, scalable, and secure storage for the data pipeline. It usually consists of large data stores like data warehouses (for structured data) and data lakes ( for structured or semi-structured data ).</p><h4>5. Data consumption</h4><p>The consumption layer delivers and integrates scalable and performant tools for consuming from the data stores. In addition, the data consumption layer provides analytics across the business for all users through purpose-built analytics tools that support analysis methodologies such as SQL, batch analytics, reporting dashboards, and machine learning.</p><h4>6. Data Governance</h4><p>The security and governance layer safeguards the data in the storage layer and all other layers’ processing resources. This layer includes access control, encryption, network security, usage monitoring, and auditing mechanisms. The security layer also keeps track of all other layers’ operations and creates a complete audit trail.</p><h3>How to Design a Data Pipeline?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsofFCDP52sCBPbORrKy4Q.png" /></figure><h4>Step 1: Determine the goal</h4><p>When designing a data pipeline, the priority is to identify the outcome or value the data pipeline will bring to your company or product. At this stage, we ask relevant questions such as:</p><ul><li>What are the requirements and objectives for this data pipeline?</li><li>How do we measure the success and data quality of the data pipeline?</li><li>What are the use cases that this will serve (reporting, analytics, machine learning)?</li></ul><h4>Step 2: Choose the data sources</h4><p>We then consider the possible data sources that will enter the data pipeline. At this stage, it’s critical to ask questions such as:</p><ul><li>What are all the potential sources of data and their ingestion formats?</li><li>How will we connect to the data sources?</li><li>Amount of data received from each data source.</li></ul><h4>Step 3: Determine the data ingestion strategy</h4><p>At this level, we need to ask questions about how the pipeline will collect the data. At this point, we ask questions such as :</p><ul><li>What communication layer will we be using to collect data ( HTTP, MQTT, gRPC)?</li><li>Would we be utilizing third-party integration tools to ingest the data?</li><li>Are we going to be using intermediate data stores to store data as it flows to the destination?</li><li>What should be the intermediate data stores?</li><li>Are we collecting data from the origin in predefined batches or in real-time?</li></ul><h4>Step 4: Design the data processing plan</h4><p>Once data has been ingested, it has to be processed and transformed for it to be valuable to downstream systems. At this stage, it’s necessary to ask questions such as:</p><ul><li>What data processing strategies are we utilizing on the data (ETL, ELT, cleaning, formatting)?</li><li>What are the tools to be used in each step?</li><li>Are we going to be enriching the data with specific attributes?</li><li>How do we remove redundant data?</li></ul><h4>Step 5: Set up storage for the output of the pipeline</h4><p>Once the data has been processed, we must determine the final storage destination for our data. At this step, we ask questions such as:</p><ul><li>Are we going to be using big data stores like data warehouses or data lakes?</li><li>Which of the data stores will serve our top use cases?</li><li>In what format will the final data be stored?</li></ul><h4>Step 6: Plan the data workflow</h4><p>We then need to design the sequencing of processes in the data pipeline. At this stage, we ask questions such as:</p><ul><li>What downstream jobs are dependent on the completion of an upstream job?</li><li>How do we handle failed jobs?</li><li>Parallel or sequential?</li></ul><h4>Step 7: Implement a data monitoring and governance framework</h4><p>At last, establish a data monitoring and governance framework, which helps us observe the data pipeline to ensure a healthy and efficient channel that’s reliable, secure, and performs as required. In this step, we determine:</p><ul><li>What needs to be logged and monitored?</li><li>How do we ensure data security?</li><li>Who is in charge of data quality?</li></ul><h3>Data Pipeline Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*4jf7ctyBPalSRgXf4inEdA.png" /></figure><h4>What is Data pipeline architecture?</h4><p>Data pipeline architecture can be defined as a system that acquires, transforms, and routes data to gain critical insights from it. A robust combination of various tools and protocols guides the data integration, transformation, and data movement across the systems.</p><p>A data pipeline architecture primarily aims to improve data quality to achieve the desired functionality and assist business intelligence and data analysis.</p><h4>Importance of data pipeline architecture</h4><ul><li><strong>Scalability:</strong> A well-designed data pipeline architecture can scale to handle increasing data volumes, preventing system failures and bottlenecks.</li><li><strong>Efficiency:</strong> Efficient data pipeline architecture processes and moves data quickly, ensuring timely and accurate data availability for decision-making.</li><li><strong>Reliability:</strong> Reliable data pipeline architecture can manage unexpected failures without data loss, ensuring accurate analysis and decision-making.</li><li><strong>Security:</strong> Secure data pipeline architecture protects against unauthorized access and malicious attacks, preventing financial loss and reputational damage.</li><li><strong>Flexibility:</strong> Flexible data pipeline architecture adapts to changes in data sources, processing needs, and analytical tools, meeting evolving business and technological requirements.</li></ul><h4>Challenges of a data pipeline architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wETy-qv1TDC0Bxql5TcP1g.png" /></figure><ol><li><strong>Data Quality:</strong> Ensuring data quality involves monitoring and validating data throughout the pipeline to maintain accuracy, consistency, and completeness, which is crucial for reliable insights and decisions.</li><li><strong>Data Volume:</strong> Managing large data volumes requires careful planning and resource allocation to avoid slow processing, bottlenecks, and system crashes.</li><li><strong>Data Integration:</strong> Effective data integration combines data from multiple sources into a unified view, addressing challenges with different formats and storage locations.</li><li><strong>Data Latency:</strong> Real-time or near-real-time processing demands a pipeline architecture capable of high-speed data ingestion, processing, and storage.</li><li><strong>Scalability:</strong> A scalable pipeline can handle increasing data volumes and processing times by adding resources as needed to prevent bottlenecks and performance issues.</li><li><strong>Security and Privacy:</strong> Securing the pipeline involves implementing access controls, encryption, and monitoring to protect sensitive data from unauthorized access and breaches.</li><li><strong>Maintenance and Management:</strong> Ongoing maintenance and management are essential to ensure pipeline efficiency, requiring a dedicated team to monitor, update, and manage dependencies and performance issues.</li></ol><h4><strong>Role of Data orchestration Tools</strong></h4><blockquote><strong>Data orchestration tools</strong> automate the process of bringing data together from multiple sources, standardizing it, and preparing it for data analysis.<br>data orchestration tools can:</blockquote><blockquote>1. Cleanse, organize, and publish data into a data warehouse</blockquote><blockquote>2. Compute business metrics</blockquote><blockquote>3. Maintain data infrastructure (like database scrapes)</blockquote><blockquote>4. Run a TensorFlow task to train a machine learning model</blockquote><blockquote>5. Apply rules to target and engage users through online marketing campaigns</blockquote><blockquote>Example Tools: Astronomer, AWS Step Functions, Azure Data Factory, Control-M, Flyte, Dagster, Google Cloud Functions, Metaflow, Apache Airflow, Prefect</blockquote><h3>Data Pipeline Architecture Best Practices</h3><ol><li><strong>Clearly Define Data Sources:</strong> Understand the types, formats, and source systems of the data (e.g., databases, APIs, flat files) before building your pipeline. This ensures the pipeline can handle data without loss or distortion, aiding in designing the initial ingestion process.</li><li><strong>Ensure Data Quality at Entry:</strong> Implement validation checks at data ingestion to detect missing values, duplicates, or anomalies, and clean the data. This prevents the propagation of corrupt or inaccurate data, ensuring reliability for downstream analytics or applications.</li><li><strong>Prioritize Scalability:</strong> Design the architecture to handle growth by choosing scalable systems and modular designs that can be easily expanded. This manages increasing data volumes and processing needs without requiring a complete redesign.</li><li><strong>Implement Robust Monitoring and Logging:</strong> Monitor data flows, detect errors, and log relevant events using tools like Prometheus, Grafana, or the ELK stack. This swiftly identifies issues to minimize downtime and ensures a clear trace of data transformations for compliance and debugging.</li><li><strong>Prioritize Data Security and Compliance:</strong> Encrypt sensitive data, implement access controls, and ensure compliance with regulations like GDPR or CCPA. This protects against data breaches, unauthorized access, and ensures regulatory compliance, safeguarding the organization’s reputation.</li><li><strong>Maintain Data Lineage and Metadata:</strong> Track data origins and transformations, and store metadata about data types, source systems, and update frequencies. This improves data trustworthiness, aids in debugging, and ensures users understand the context and limitations of the data.</li><li><strong>Choose the Right Processing Paradigm:</strong> Decide between batch, real-time, or hybrid processing based on the use case, and incorporate CI/CD principles. This ensures timely data availability, optimizes costs, and enhances system performance.</li><li><strong>Ensure Data Redundancy and Disaster Recovery:</strong> Implement backup mechanisms and a disaster recovery plan, considering distributed storage solutions and regular backups. This prevents permanent data loss and ensures swift service restoration, minimizing downtime.</li><li><strong>Opt for Flexibility and Modularity:</strong> Design modular pipelines where components can be added, removed, or swapped without impacting the entire system. This adapts to changing business requirements and new data sources without major overhauls, saving time and resources.</li><li><strong>Test Regularly and Thoroughly:</strong> Regularly conduct unit tests, integration tests, and performance tests, and gather feedback from end-users and stakeholders. This catches issues before they become critical, ensures data reliability, and maintains optimal system performance as data volumes grow.</li></ol><p>These best practices provide a foundation for ensuring the reliability, efficiency, and longevity of a data pipeline architecture, tailored to organizational needs.</p><h3>Concusion</h3><p>Implementing a robust data pipeline architecture is crucial for any organization aiming to leverage data effectively for decision-making and insights. By clearly defining data sources, ensuring data quality at entry, and prioritizing scalability, organizations can build resilient systems that grow with their data needs. Robust monitoring, logging, and security measures protect against data loss and breaches, while maintaining data lineage and metadata ensures transparency and trustworthiness.</p><p>Choosing the right processing paradigm, ensuring redundancy and disaster recovery, and opting for flexibility and modularity prepare the pipeline for future changes and challenges. Regular and thorough testing guarantees reliability and optimal performance. By following these best practices, organizations can create data pipelines that are not only efficient and reliable but also adaptable to evolving business requirements and technological advancements, thus ensuring long-term success and data-driven growth.</p><p>References</p><ul><li><a href="https://atlan.com/data-transformation-101/?ref=/data-pipeline-architecture/">https://atlan.com/data-transformation-101/?ref=/data-pipeline-architecture/</a></li><li><a href="https://estuary.dev/data-pipeline-architecture/">https://estuary.dev/data-pipeline-architecture/</a></li><li><a href="https://www.striim.com/blog/what-is-a-data-pipeline-and-must-have-features-of-modern-data-pipelines/">https://www.striim.com/blog/what-is-a-data-pipeline-and-must-have-features-of-modern-data-pipelines/</a></li><li><a href="https://www.fivetran.com/learn/data-pipeline-architecture">https://www.fivetran.com/learn/data-pipeline-architecture</a></li><li><a href="https://atlan.com/data-pipeline-monitoring/?ref=/data-pipeline-architecture/">https://atlan.com/data-pipeline-monitoring/?ref=/data-pipeline-architecture/</a></li><li><a href="https://atlan.com/data-pipeline-architecture/">https://atlan.com/data-pipeline-architecture/</a></li><li><a href="https://atlan.com/forrester-wave-enterprise-data-catalog-for-dataops-2022/?ref=/data-pipeline-architecture/">https://atlan.com/forrester-wave-enterprise-data-catalog-for-dataops-2022/?ref=/data-pipeline-architecture/</a></li><li><a href="https://www.montecarlodata.com/blog-data-pipeline-architecture-explained/">https://www.montecarlodata.com/blog-data-pipeline-architecture-explained/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06a6eaa867ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CCP Certification Essentials Part-10 (Understanding AWS Pricing, Billing, and Governance, and…]]></title>
            <link>https://cudakara.medium.com/aws-ccp-certification-essentials-part-10-understanding-aws-pricing-billing-and-governance-and-aaaffb60fa8f?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaaffb60fa8f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-pricing]]></category>
            <category><![CDATA[aws-billing]]></category>
            <category><![CDATA[aws-certification]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 17:05:57 GMT</pubDate>
            <atom:updated>2023-06-09T17:05:57.646Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CCP Certification Essentials Part-10 (Understanding AWS Pricing, Billing, and Governance, and AWS Support plans)</h3><p>Navigating the world of cloud services can be daunting, especially when it comes to understanding the costs associated with them. One of the major players in this realm is Amazon Web Services (AWS). AWS offers a range of services each with its own unique pricing structure. Here, we will delve into the fundamentals of AWS pricing, its billing structure, and how you can govern your expenses effectively.</p><h4>Fundamentals of AWS Pricing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMLWEFBZjBlNuXx9NbmPUQ.png" /></figure><p>AWS costs are primarily driven by three key factors:</p><p><strong>1. Compute</strong> — This refers to the time and resources consumed by your applications from launch to termination. It’s billed hourly.<br><strong>2. Storage</strong>— Storage costs come into play with the data you store in the cloud.<br><strong>3. Outbound Transfer</strong>— These costs apply to data “in flight” or moving between systems.</p><h4>AWS Free Offer Types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*oqE9AF3w3AtLR9jqCJA8lw.png" /></figure><p>To attract and retain customers, AWS provides several free offer types:</p><p><strong>1. 12 months free </strong>— This offer gives new AWS users 12 months of free usage following the initial sign-up date.<br><strong>2. Always free</strong> — These offers do not expire and are available to all AWS customers.<br><strong>3. Trials</strong>— Short-term free trials start from the date you activate a particular service.</p><h3>AWS Service-Specific Pricing</h3><p>Different AWS services have different pricing structures. Here, we look at the pricing details for EC2, Lambda, S3, and RDS.</p><h4>EC2 Pricing<br>EC2 pricing models include:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*u_kpzqEGChuuIJ6A83UhVQ.png" /></figure><p>- On-Demand<br>- Savings Plan<br>- Reserved Instances<br>- Spot Instances<br>- Dedicated Hosts</p><h4>Lambda Pricing<br>Lambda pricing is determined by:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KV_ux1Xne1y5lHvq6HS8Jw.png" /></figure><p>- Number of requests: Includes test invokes from the console.<br>- Code execution time: Calculated from execution start, in response to events, to stop.<br>- Always free: AWS provides 1 million requests per month for free.</p><h4>S3 Pricing<br>S3 costs are calculated based on:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWTsN4ub886U3o5lswsPMg.png" /></figure><p>- Storage class<br>- Storage: Determined by the number and size of objects<br>- Data transfer: Data transferred out of the S3 Region<br>- Request and data retrieval: Based on requests made for data and the amount of requests</p><h4>RDS Pricing<br>RDS costs are determined by:</h4><p>- Running clock hours<br>- Database type<br>- Purchase type<br>- Storage<br>- API requests<br>- Database Count<br>- Deployment type<br>- Data transfer</p><h3>Understanding the Total Cost of Ownership (TCO)</h3><p>TCO is a financial estimate that helps you understand both the direct and indirect costs of AWS. It includes two key AWS services:</p><h4>Application Discovery Service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*FYPm3oDhyku5jaBzOZzkxw.png" /></figure><p>This service helps you plan migration projects to the AWS Cloud. It works with other services to migrate servers and is used to estimate TCO.</p><h4>AWS Price List API</h4><p>The Price List API allows you to query the price of AWS services. You can receive price alerts when prices change and query using JSON or HTML.</p><h3>Navigating AWS Support Plans: A Comprehensive Guide</h3><p>Amazon Web Services (AWS) is a complex and powerful toolset that is often used to run vital business operations. Given the importance and intricacy of the platform, having reliable support is essential. AWS offers four distinct support plans to cater to the diverse needs of its users. These include Basic, Developer, Business, and Enterprise. In this blog, we will detail each of these support plans, outlining their respective costs, features, and recommendations to help you make an informed decision.</p><h4>Types of AWS Support Cases</h4><p>There are three types of AWS support cases:</p><ol><li><strong>Account and Billing</strong> — All customers, irrespective of their support plans, can open account-related and billing cases.</li><li><strong>Service Limit Increases</strong> — All customers can request default service quota (or limit) increases.</li><li><strong>Technical Support</strong> — Technical support cases can only be opened by customers on the Developer, Business, or Enterprise plans.</li></ol><h3>AWS Support Plans</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oiq_clgqRoPcBdzECF3pQ.jpeg" /></figure><h3>1. Basic Support Plan</h3><p>All AWS accounts include the Basic Support Plan for free. This plan provides:</p><ul><li>Support case types: Account and billing and service limit increases.</li><li>Customer Service: 24/7 access via email only.</li></ul><p>This plan is perfect for users who are just getting started with AWS and do not require technical assistance.</p><h3>2. Developer Support Plan</h3><p>Starting at $29 per month, the Developer Support Plan is designed for testing and development. Key features include:</p><ul><li>Support case types: Account and billing, Service limit increases, and technical support.</li><li>One primary contact.</li><li>Unlimited cases.</li><li>Cloud Support Associate: Business-hours access via email only.</li><li>Response times: General guidance (&lt; 24 hours), System impaired (&lt; 12 hours).</li></ul><p>This plan is ideal for developers who require technical support during their business hours.</p><h3>3. Business Support Plan</h3><p>The Business Support Plan, starting at $100 per month, is recommended for production workloads. This plan includes:</p><ul><li>Support case types: Account and billing, Service limit increases, and technical support.</li><li>Unlimited contacts and cases.</li><li>Full set of Trusted Advisor checks.</li><li>Cloud Support Associate: 24/7 access via email, phone, or chat.</li><li>Response times: General guidance (&lt; 24 hours), System impaired (&lt; 12 hours), Production System impaired (&lt; 4 hours), Production System down (&lt; 1 hour).</li></ul><p>This plan is designed for businesses with production workloads and requiring 24/7 support coverage.</p><h3>4. Enterprise Support Plan</h3><p>Starting at $15,000 per month, the Enterprise Support Plan is tailored for business or mission-critical production workloads. The comprehensive features include:</p><ul><li>Support case types: Account and billing, Service limit increases, and technical support.</li><li>Unlimited contacts and cases.</li><li>Full set of Trusted Advisor checks.</li><li>Dedicated Technical Account Manager (TAM).</li><li>Access to a Concierge Support Team.</li><li>Infrastructure Event Management.</li><li>Cloud Support Associate: 24/7 access via email, phone, or chat.</li><li>Response times: General guidance (&lt; 24 hours), System impaired (&lt; 12 hours), Production System impaired (&lt; 4 hours), Production System down (&lt; 1 hour), Business-critical system down (&lt; 15 mins).</li></ul><p>This premium plan is designed for businesses that consider AWS to be mission-critical and require the fastest response times and a dedicated support team.</p><p>In conclusion, the right AWS Support Plan for your business will depend on your requirements, budget, and the criticality of your business operations.</p><p>Aaaaannnnddd, That’s it for this article after a long time of silence. Hope you have enjoyed this article! 😁 Looking forward to our next encounter, where we’ll delve into AWS Pricing, billing and Governance services. Until then, cheers! 🍻</p><h3>References</h3><ul><li><a href="https://aws.amazon.com/lambda/pricing/">Serverless Computing - AWS Lambda Pricing - Amazon Web Services</a></li><li><a href="https://docs.aws.amazon.com/whitepapers/latest/how-aws-pricing-works/key-principles.html">Key principles</a></li><li><a href="https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&amp;all-free-tier.sort-order=asc&amp;awsf.Free%20Tier%20Types=*all&amp;awsf.Free%20Tier%20Categories=*all">Free Cloud Computing Services - AWS Free Tier</a></li><li><a href="https://aws.amazon.com/s3/pricing/">S3 Pricing</a></li><li><a href="https://aws.amazon.com/application-discovery/">Discovery for Migration Planning- AWS Application Discovery Service - Amazon Web Services</a></li><li><a href="https://aws.amazon.com/premiumsupport/plans/">AWS Support Plans | Compare plans, get technical assistance, and receive expert guidance</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaaffb60fa8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CCP Certification Essentials Part-09 (Application Security and Data Encryption and Secrets…]]></title>
            <link>https://cudakara.medium.com/aws-ccp-certification-essentials-part-09-application-security-and-data-encryption-and-secrets-ea25648481cd?source=rss-3a99f0885f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea25648481cd</guid>
            <category><![CDATA[aws-kms]]></category>
            <category><![CDATA[aws-ccp]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[aws-security]]></category>
            <dc:creator><![CDATA[Chamindu Udakara]]></dc:creator>
            <pubDate>Fri, 05 May 2023 07:08:49 GMT</pubDate>
            <atom:updated>2023-05-05T07:08:49.828Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CCP Certification Essentials Part-09 (Application Security and Data Encryption and Secrets Management Services)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*oEURvPcQYtiQNx-SScCOtg.jpeg" /></figure><h3>Application Security Services</h3><p>In today’s world, online security is of the utmost importance. With the increasing number of cyber attacks, businesses need to ensure that their web applications and data are protected. Luckily, Amazon Web Services (AWS) offers several tools and services to help businesses safeguard their online assets. In this blog post, we will explore seven AWS security tools that can help protect your web applications and data.</p><h4>1. AWS Web Application Firewall (WAF)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4u8dc2ffSNBL1uCQe3YC6w.png" /></figure><p>Web Application Firewall (WAF) is an AWS security tool that helps protect your web applications against common web attacks. It protects your apps against common attack patterns, such as SQL injection and cross-site scripting. WAF works by inspecting web traffic to your applications and blocking malicious requests before they reach your servers. This helps prevent attacks and keeps your applications running smoothly.</p><h4>Distributed Denial of Service (DDoS)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQ_XgF1hz3sv25XiMVmuKw.png" /><figcaption>DDOS</figcaption></figure><p>Distributed Denial of Service (DDoS) is a type of cyber attack that is designed to overwhelm a website or web application with traffic, making it unavailable to its intended users. In a DDoS attack, the attacker uses a network of computers, often referred to as a botnet, to send a large volume of traffic to the target website or application. This traffic flood is intended to consume the target’s resources, such as bandwidth and processing power, and cause the website or application to become unavailable to legitimate users.</p><p>DDoS attacks can be launched for various reasons, including to extort money from a business, to disrupt competition, or to make a political statement. The attack can be launched from anywhere in the world, making it difficult to identify and stop the attacker. As technology has advanced, so have DDoS attacks, and they now have the potential to cause significant damage to businesses of all sizes.</p><p>To protect against DDoS attacks, businesses can use services like AWS Shield, which provides always-on detection and protection against DDoS attacks.</p><h4>2. AWS Shield</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*14b7oP4RJYcRx_94JtwxBg.png" /></figure><p>Shield is a managed Distributed Denial of Service (DDoS) protection service. A DDoS attack causes a traffic jam on a website or web application in an attempt to cause it to crash. Shield protects your applications against DDoS attacks by providing always-on detection. Shield Standard is a free service that comes with all AWS accounts. If you need additional protection, Shield Advanced is a paid service that provides enhanced DDoS protection. Shield Advanced supports several AWS services, including CloudFront, Route 53, Elastic Load Balancing, and AWS Global Accelerator.</p><h4>3. AWS Macie</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eoQmvaGbR3BrepTZnszBGQ.png" /></figure><p>Macie is an AWS security tool that helps you discover and protect sensitive data. It uses machine learning to evaluate your S3 environment and uncover personally identifiable information (PII). Macie helps you maintain compliance with regulations by identifying and classifying sensitive data. It also provides alerts when it detects suspicious activity.</p><h4>4. AWS Config</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*svKn_t-CUL802TgfnEeA7Q.png" /></figure><p>Config is an AWS security tool that allows you to assess, audit, and evaluate the configurations of your resources. It tracks configuration changes over time and delivers a configuration history file to S3. Config also provides notifications via Simple Notification Service (SNS) of every configuration change. This helps you maintain compliance with regulations and identify potential security issues.</p><h4>5. AWS GuardDuty</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Z8jwRYZkfv2MNO9xmlOzgw.png" /></figure><p>GuardDuty is an intelligent threat detection system that uncovers unauthorized behaviour. It uses machine learning to review CloudTrail, VPC Flow Logs, and DNS logs to identify threats. GuardDuty provides built-in detection for EC2, S3, and IAM. It also provides alerts when it detects suspicious activity.</p><h4>6. AWS Inspector</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9mlwYf1db_IJVm7ScrpF8g.png" /></figure><p>Inspector is an AWS security tool that works with EC2 instances to uncover and report vulnerabilities. It requires an agent to be installed on the EC2 instance and then reports on vulnerabilities found. Inspector checks access from the internet, remote root login, vulnerable software versions, and other potential vulnerabilities. This helps you identify and address potential security issues.</p><h4>7. AWS Artifact</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PMA2NPEMdT1BJS38AnIdEQ.png" /></figure><p>Artifact is an AWS security tool that offers on-demand access to AWS security and compliance reports. It serves as a central repository for compliance reports from third-party auditors, such as Service Organization Controls (SOC) reports and Payment Card Industry (PCI) reports. This makes it easy for you to maintain compliance with regulations and provide evidence of compliance to auditors.</p><h4>Conclusion</h4><p>In conclusion, AWS offers several security tools that can help you protect your web applications and data. By using these tools, you can maintain compliance with regulations and identify and address potential security issues. From protecting against common web attacks with WAF, to uncovering vulnerabilities with Inspector, and maintaining compliance with Artifact, AWS has you covered.</p><h3>Data Encryption and Secrets Management Services</h3><h4>Data in Flight vs. Data at Rest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*qgR7IA9WmG9-WB5sublOAw.png" /></figure><p>Data security is a top priority for businesses of all sizes, and one critical aspect of data security is understanding the difference between data in flight and data at rest. Data in flight refers to data that is actively moving from one location to another, such as when data is transmitted over a network. Data at rest, on the other hand, refers to data that is stored and inactive or stored for later use.</p><p>AWS offers a range of services to help protect both data in flight and data at rest, including:</p><h4>1. AWS Key Management Service (KMS)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*N0I-85pVy-xKHs34Wv8rhw.png" /></figure><p>KMS is a service that allows you to generate and store encryption keys, which can help protect your data at rest. With KMS, you can create and manage keys, and AWS manages the encryption keys for you. KMS is automatically enabled for certain AWS services, such as Amazon S3 and Amazon EBS, and you can also use it with your own applications. By using KMS, you can help ensure that your data at rest is protected.</p><h4>2. AWS CloudHSM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1DscCgUuSr811dBLXVJ7wA.png" /></figure><p>CloudHSM is a hardware security module (HSM) that can be used to generate encryption keys for both data at rest and data in flight. CloudHSM provides dedicated hardware for security and allows you to generate and manage your own encryption keys, which means that AWS does not have access to your keys. CloudHSM is a good choice for organizations that have strict security requirements or that need to comply with regulations like HIPAA or PCI.</p><h4>3. AWS Secrets Manager</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ykHligKjZvVryzUqsWDwFA.png" /></figure><p>Secrets Manager is a service that allows you to manage and retrieve secrets, such as passwords or API keys, which can help protect your data in flight. With Secrets Manager, you can rotate, manage, and retrieve secrets, and the service encrypts secrets at rest. Secrets Manager integrates with a variety of AWS services, including Amazon RDS, Amazon Redshift, and Amazon DocumentDB, which makes it easy to use and deploy.</p><p>By using these services, you can help ensure that your data is secure and protected from unauthorized access or theft.</p><p>Aaaaannnnddd, That&#39;s it for security and key management services in AWS. Hope you have enjoyed this article! 😁 We will meet again with the next chapter which is Pricing in AWS. Cheers!! 🍻</p><h4>References</h4><ul><li><a href="https://aws.amazon.com/security/">AWS Cloud Security</a></li><li><a href="https://aws.amazon.com/config/">Config Tool - AWS Config - Amazon Web Services</a></li><li><a href="https://aws.amazon.com/shield/">Managed DDos Protection - AWS Shield - AWS</a></li><li><a href="https://aws.amazon.com/inspector/">Automated Vulnerability Management - Amazon Inspector - AWS</a></li><li><a href="https://aws.amazon.com/guardduty/">Intelligent Threat Detection - Amazon GuardDuty - AWS</a></li><li><a href="https://aws.amazon.com/macie/">Sensitive Data Discovery and Protection - Amazon Macie - AWS</a></li><li><a href="https://aws.amazon.com/products/security/">Cloud Security, Identity, and Compliance Products - Amazon Web Services (AWS)</a></li><li><a href="https://aws.amazon.com/kms">Encryption Cryptography Signing - AWS Key Management Service - AWS</a></li><li><a href="https://aws.amazon.com/cloudhsm">Security HSM - AWS CloudHSM - AWS</a></li><li><a href="https://aws.amazon.com/artifact">Security Compliance Management - AWS Artifact - AWS</a></li><li><a href="https://aws.amazon.com/secrets-manager">Cloud Password Management - AWS Secrets Manager - AWS</a></li><li><a href="https://aws.amazon.com/waf/">Web Application Firewall, Web API Protection - AWS WAF - AWS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea25648481cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>