<?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"><channel><title><![CDATA[Archboard Blog]]></title><description><![CDATA[Archboard Blog]]></description><link>https://archboard.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6afed1c7129268dc97b0125d/0a5d2011-4b03-408b-84f4-6bc92412713b.png</url><title>Archboard Blog</title><link>https://archboard.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 13:06:12 GMT</lastBuildDate><atom:link href="https://archboard.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[OAuth 2.0 Flow Diagram: Authorization Code with PKCE, Step by Step]]></title><description><![CDATA[A step-by-step OAuth 2.0 flow diagram for authorization code with PKCE: redirects, state, code_verifier, tokens, refresh and common mistakes.]]></description><link>https://archboard.hashnode.dev/oauth-2-0-flow-diagram-authorization-code-with-pkce-step-by-step</link><guid isPermaLink="true">https://archboard.hashnode.dev/oauth-2-0-flow-diagram-authorization-code-with-pkce-step-by-step</guid><category><![CDATA[oauth]]></category><category><![CDATA[Security]]></category><category><![CDATA[authentication]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Halil Öncen]]></dc:creator><pubDate>Tue, 24 Nov 2026 11:48:59 GMT</pubDate><content:encoded><![CDATA[<p>OAuth 2.0 is easy to use and hard to picture. A login button triggers redirects between three or four parties, each carrying parameters with similar names, and most bugs come from one party skipping a check it was supposed to make. A sequence diagram is the clearest way to see who sends what to whom, and in which order.</p>
<p>This post draws the flow you should use today for almost every client: the authorization code grant with PKCE. It walks through each step, explains what each party checks, and lists the older flows that current guidance tells you to drop.</p>
<h2>The four parties</h2>
<table>
<thead>
<tr>
<th>Role in the spec</th>
<th>In practice</th>
<th>Holds</th>
</tr>
</thead>
<tbody><tr>
<td>Resource owner</td>
<td>The user</td>
<td>Their credentials</td>
</tr>
<tr>
<td>Client</td>
<td>Your web app, single-page app or mobile app</td>
<td>The tokens it receives</td>
</tr>
<tr>
<td>Authorization server</td>
<td>Your identity provider</td>
<td>User accounts, consent, signing keys</td>
</tr>
<tr>
<td>Resource server</td>
<td>Your API</td>
<td>The data, and the rules for which tokens it accepts</td>
</tr>
</tbody></table>
<p>The client never sees the user's password. That is the point of OAuth: the authorization server authenticates the user and hands the client a token with limited scope and lifetime.</p>
<h2>Which flow, in 2026</h2>
<p>The original <a href="https://www.rfc-editor.org/rfc/rfc6749.html">OAuth 2.0 framework, RFC 6749</a>, defined several grants. The <a href="https://www.rfc-editor.org/rfc/rfc9700.html">OAuth 2.0 Security Best Current Practice, RFC 9700</a>, published in January 2025, narrows the choice:</p>
<ul>
<li><strong>Authorization code with PKCE</strong> for user sign-in, from any kind of client. Public clients (mobile apps, single-page apps) must use PKCE; for confidential clients with a server-side secret it is recommended.</li>
<li><strong>Not the implicit grant.</strong> It returns tokens in the browser redirect, where they can leak; clients should not use it.</li>
<li><strong>Not the resource owner password credentials grant.</strong> Handing the user's password to the client defeats the purpose; the BCP says it must not be used.</li>
<li><strong>Client credentials</strong> for service-to-service calls with no user involved.</li>
</ul>
<p>The OAuth 2.1 draft consolidates these rules into one document, so new libraries increasingly assume them.</p>
<h2>PKCE in one paragraph</h2>
<p><a href="https://www.rfc-editor.org/rfc/rfc7636.html">Proof Key for Code Exchange, RFC 7636</a>, protects the authorization code. Before redirecting, the client creates a random <code>code_verifier</code> (43 to 128 characters) and sends only its SHA-256 hash, the <code>code_challenge</code>, with <code>code_challenge_method=S256</code>. When the client later exchanges the code for tokens, it sends the verifier. The server hashes it and compares. An attacker who intercepts the code cannot use it without the verifier, which never left the client.</p>
<h2>The flow, step by step</h2>
<ol>
<li><strong>The user clicks Sign in.</strong> The client generates <code>state</code> (a random value tied to the user's session) and the PKCE verifier and challenge.</li>
<li><strong>The client redirects to <code>/authorize</code></strong> with <code>response_type=code</code>, <code>client_id</code>, the registered <code>redirect_uri</code>, the requested <code>scope</code>, <code>state</code> and the code challenge.</li>
<li><strong>The authorization server shows its login and consent page.</strong> The client is not involved; this happens on the server's domain.</li>
<li><strong>The user signs in,</strong> completes MFA if required, and consents to the scopes.</li>
<li><strong>The server redirects back</strong> to the exact registered <code>redirect_uri</code> with a short-lived, single-use <code>code</code> and the same <code>state</code>. The client checks that <code>state</code> matches what it sent; if not, it stops. RFC 6749 recommends a code lifetime of at most 10 minutes.</li>
<li><strong>The client posts to <code>/token</code></strong> with the code, the redirect URI and the <code>code_verifier</code> (plus its client authentication, if it is a confidential client). This is a back-channel request, not a redirect.</li>
<li><strong>The server returns tokens:</strong> an access token, usually a refresh token, and an ID token if you use OpenID Connect.</li>
<li><strong>The client calls the API</strong> with <code>Authorization: Bearer &lt;access token&gt;</code>.</li>
<li><strong>The API validates the token</strong> and responds. For JWT access tokens it checks the signature, issuer, audience, expiry and scopes locally; for opaque tokens it asks the authorization server's introspection endpoint.</li>
<li><strong>When the access token expires,</strong> the client posts the refresh token to <code>/token</code>.</li>
<li><strong>The server returns a new access token,</strong> and for public clients a new refresh token. RFC 9700 requires refresh tokens for public clients to be either sender-constrained or rotated, so a stolen refresh token stops working after one use by either party.</li>
</ol>
<h2>The sequence diagram</h2>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/hue1603ptxp06jupm7uu.png" alt="A sequence diagram with a user, a client app, an authorization server and an API. The client sends the user to authorize with a code challenge and state, gets a code back, exchanges code and verifier for tokens, calls the API with a bearer token and later refreshes it." /></p>
<p><em>The authorization code flow with PKCE as a sequence diagram. The client sends a code challenge with the authorization request, proves it holds the matching verifier when it exchanges the code, and uses the access token at the API until it refreshes it.</em></p>
<p>How to read it:</p>
<ul>
<li><strong>Four lifelines,</strong> left to right: the user, the client app, the authorization server and the API.</li>
<li><strong>Solid arrows with filled heads</strong> are requests; <strong>dashed arrows</strong> are responses and redirects back.</li>
<li><strong>Steps 2 to 5</strong> are front-channel redirects through the browser; <strong>step 6</strong> is the back-channel token request where PKCE pays off.</li>
<li><strong>The opt fragment</strong> at the bottom only runs when the access token has expired.</li>
<li><strong>The Markdown block</strong> lists the checks each party makes, which is where most real bugs hide.</li>
</ul>
<h2>Mistakes that show up in reviews</h2>
<ul>
<li><strong>Not checking <code>state</code>.</strong> Without it, an attacker can complete a login flow in the victim's browser with the attacker's account.</li>
<li><strong>Loose redirect URI matching.</strong> The server must compare against the registered URI exactly; prefix or wildcard matching enables code theft.</li>
<li><strong>Tokens in local storage of a single-page app.</strong> Any script injection can read them. Many teams put a small backend in front of the SPA (a backend-for-frontend) that holds tokens and gives the browser a session cookie.</li>
<li><strong>APIs that accept any valid token.</strong> Check the audience, or a token issued for another API will work on yours.</li>
<li><strong>Embedded web views in mobile apps.</strong> <a href="https://www.rfc-editor.org/rfc/rfc8252.html">RFC 8252</a> says native apps should use the system browser, so the app cannot see the user's credentials.</li>
<li><strong>Long-lived access tokens to avoid refresh logic.</strong> Keep access tokens short and refresh them; revocation then takes effect quickly.</li>
</ul>
<h2>What to draw on an OAuth diagram</h2>
<ul>
<li><strong>Every party as its own lifeline,</strong> including the browser if your client has a backend.</li>
<li><strong>Front channel and back channel</strong> distinguished, because they have different security properties.</li>
<li><strong>Parameter names on the arrows:</strong> <code>state</code>, <code>code_challenge</code>, <code>code</code>, <code>code_verifier</code>. Reviewers look for them.</li>
<li><strong>Who validates what.</strong> The checks are the design; the arrows only move data around.</li>
</ul>
<p>If you are drawing the wider security picture, the <a href="https://getarchboard.app/blog/zero-trust-architecture-diagram">zero trust architecture diagram</a> shows where the identity provider sits among the other controls, and the <a href="https://getarchboard.app/blog/api-gateway-architecture-diagram">API gateway architecture diagram</a> covers validating tokens once at the edge. The <a href="https://getarchboard.app/blog/sequence-diagram-example">sequence diagram example</a> explains the notation used here in more depth.</p>
<h2>Build it in Archboard</h2>
<ol>
<li>Sign in with Google or GitHub and create a diagram.</li>
<li>From the <strong>Sequence</strong> pack, add an <strong>Actor</strong> for the user and three <strong>Lifeline</strong> nodes for the client app, the authorization server and the API, in one row with the same height.</li>
<li>Draw each message as a straight edge between lifelines, top to bottom, with the parameter names in the label. Use dashed edges with open arrowheads for responses and redirects.</li>
<li>Add a <strong>Fragment</strong> with the <code>opt</code> operator around the refresh steps.</li>
<li>Add a <strong>Markdown</strong> block from the <strong>Core</strong> pack with the checks each party makes.</li>
</ol>
<p>The example uses 6 diagram nodes, within the Free plan.</p>
<h2>FAQ</h2>
<p><strong>What is the difference between OAuth 2.0 and OpenID Connect?</strong> OAuth 2.0 is about delegated access: the client gets a token to call an API. OpenID Connect adds identity on top: an ID token that tells the client who the user is, and a standard user info endpoint.</p>
<p><strong>Do I need PKCE if my app has a client secret?</strong> RFC 9700 recommends it for confidential clients too. It protects against code injection and costs one extra parameter on each side.</p>
<p><strong>Should the implicit grant still be used?</strong> No. Current best practice says clients should not use it. Use the authorization code grant with PKCE instead, also in single-page apps.</p>
<p><strong>Where should a single-page app store tokens?</strong> Preferably not in the browser at all: a backend-for-frontend can keep tokens server-side and give the browser a secure session cookie. If tokens must live in the browser, keep them in memory, keep access tokens short and use refresh token rotation.</p>
<p><strong>How does the API validate an access token?</strong> For JWT access tokens, by checking the signature with the authorization server's published keys plus issuer, audience, expiry and scope. For opaque tokens, by calling the introspection endpoint.</p>
<hr />
<p><em>This post was originally published on the <a href="https://getarchboard.app/blog/oauth-2-flow-diagram">Archboard blog</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[How to Draw a Kubernetes Architecture Diagram (with Free Template)]]></title><description><![CDATA[What a Kubernetes architecture diagram should show, how to pick detail by audience, mistakes to avoid, and how to build one from a free template.]]></description><link>https://archboard.hashnode.dev/how-to-draw-a-kubernetes-architecture-diagram-with-free-template</link><guid isPermaLink="true">https://archboard.hashnode.dev/how-to-draw-a-kubernetes-architecture-diagram-with-free-template</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[Devops]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Halil Öncen]]></dc:creator><pubDate>Mon, 23 Nov 2026 11:49:49 GMT</pubDate><content:encoded><![CDATA[<p>Most Kubernetes diagrams fail in one of two ways: they are a wall of Pod icons nobody can read, or a three-box sketch that says "cluster" and little else. A useful Kubernetes architecture diagram sits in between. It shows where traffic enters, which objects route it, where state lives and which boundaries matter, at a level of detail that fits the person reading it.</p>
<p>This guide covers what to include, how to choose detail by audience, the mistakes that make diagrams useless, and how to build one step by step in Archboard. The free template opens as a new diagram in your own workspace in one click.</p>
<h2>What a useful Kubernetes architecture diagram shows</h2>
<p>The Kubernetes docs describe the <a href="https://kubernetes.io/docs/concepts/overview/components/">cluster components</a>: control plane, kubelet, kube-proxy and so on. That is the platform view. Most teams need the workload view: how <em>your</em> application runs on the cluster. Five things carry most of the value.</p>
<h3>1. Cluster and namespace boundaries</h3>
<p>Draw the cluster as the outer boundary and namespaces as frames inside it. Namespaces are where RBAC, resource quotas and most NetworkPolicies apply, so they are the boundaries people ask about first ("is payments in its own namespace?"). If you run several clusters (prod and staging, or one per region), give each its own boundary and label it with name and environment.</p>
<h3>2. North-south traffic</h3>
<p>Show the request path from outside the cluster inward:</p>
<p>Client → Ingress → Service → Deployment → Pods</p>
<p>Make the direction explicit with arrows. Note the Ingress host and path rules and the Service type and port. This one path answers most "where does this request go?" questions during an incident.</p>
<p>East-west traffic (service to service inside the cluster) matters too, but draw it selectively: the calls that cross namespaces or sit on the critical path.</p>
<h3>3. Config and storage</h3>
<p>Attach ConfigMaps, Secrets and PersistentVolumeClaims to the workloads that use them. A Deployment with a Secret and a PVC tells the reader two things: this workload holds credentials, and it has state that outlives a Pod. Draw external state, such as a managed Postgres, outside the cluster boundary so it is clear what the cluster owns and what it doesn't.</p>
<h3>4. Scaling</h3>
<p>Put a HorizontalPodAutoscaler next to the Deployment it targets, with min/max replicas and the metric in its name or a note ("2–10, CPU 70%"). That says more than ten drawn Pods.</p>
<h3>5. NetworkPolicy</h3>
<p>If you use NetworkPolicies, show which ones apply and what they allow. A security reviewer wants to see "only the api namespace can reach Postgres", not infer it.</p>
<h2>How manifests map to diagram nodes</h2>
<p>Take three ordinary objects:</p>
<pre><code class="language-yaml">apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  namespace: shop
spec:
  replicas: 3
  selector:
    matchLabels: { app: orders-api }
  template:
    metadata:
      labels: { app: orders-api }
    spec:
      containers:
        - name: api
          image: registry.example.com/orders-api:1.4.2
          ports: [{ containerPort: 8080 }]
          envFrom: [{ secretRef: { name: orders-db } }]
---
apiVersion: v1
kind: Service
metadata:
  name: orders-api
  namespace: shop
spec:
  selector: { app: orders-api }
  ports: [{ port: 80, targetPort: 8080 }]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop
  namespace: shop
spec:
  rules:
    - host: shop.example.com
      http:
        paths:
          - path: /orders
            pathType: Prefix
            backend:
              service: { name: orders-api, port: { number: 80 } }
</code></pre>
<p>On the diagram they become:</p>
<table>
<thead>
<tr>
<th>Manifest</th>
<th>Diagram node</th>
<th>Name or note</th>
</tr>
</thead>
<tbody><tr>
<td><code>namespace: shop</code></td>
<td>Namespace frame</td>
<td><code>shop</code></td>
</tr>
<tr>
<td>Ingress <code>shop</code></td>
<td>Ingress</td>
<td><code>shop.example.com/orders</code></td>
</tr>
<tr>
<td>Service <code>orders-api</code></td>
<td>Service</td>
<td><code>ClusterIP :80 → 8080</code></td>
</tr>
<tr>
<td>Deployment <code>orders-api</code></td>
<td>Deployment</td>
<td><code>orders-api ×3, v1.4.2</code></td>
</tr>
<tr>
<td><code>secretRef: orders-db</code></td>
<td>Secret</td>
<td><code>orders-db</code></td>
</tr>
</tbody></table>
<p>Three replicas become one Deployment node with "×3", not three Pod boxes. The edges follow the references in the YAML: Ingress backend → Service, Service selector → Deployment, <code>envFrom</code> → Secret.</p>
<h2>Choose the level of detail by audience</h2>
<p>One diagram rarely serves everyone. Decide who it is for before you draw.</p>
<table>
<thead>
<tr>
<th>Audience</th>
<th>Needs</th>
<th>Include</th>
<th>Leave out</th>
</tr>
</thead>
<tbody><tr>
<td>On-call engineer</td>
<td>Fast path from symptom to component</td>
<td>Ingress → Service → Deployment chain, external dependencies, HPA limits, namespace names</td>
<td>Labels, annotations, every ConfigMap</td>
</tr>
<tr>
<td>New hire</td>
<td>A mental model of the system</td>
<td>Namespaces, main services, data stores, a short note per area</td>
<td>Replica counts, NetworkPolicy details</td>
</tr>
<tr>
<td>Security review</td>
<td>Trust boundaries and data flows</td>
<td>Namespaces, NetworkPolicies, Secrets, Ingress and TLS, egress to external systems</td>
<td>Scaling details</td>
</tr>
</tbody></table>
<p>If two audiences need different things, draw two views rather than one diagram that tries to do everything.</p>
<h2>Common mistakes</h2>
<ul>
<li><strong>Drawing every Pod replica.</strong> Replicas are a number, not architecture. One Deployment node with a replica count, plus an HPA if it scales, reads better than a grid of identical boxes.</li>
<li><strong>Mixing logical and physical.</strong> Worker nodes, zones and Pod placement are a physical view; Ingress → Service → Deployment is a logical view. Put both on one canvas and neither is readable. If you need the physical view, make it a separate diagram.</li>
<li><strong>No traffic direction.</strong> Lines without arrows don't say who calls whom. Use directed edges and keep the main request flow moving one way, left to right or top to bottom.</li>
<li><strong>Stale diagrams.</strong> A diagram showing last year's services does more harm than none. Put an owner and a "last checked" date on the canvas, and update it when a change adds or removes a box.</li>
<li><strong>Unexplained edges.</strong> "Service → Deployment" is obvious; "orders-api → payments-api" deserves a protocol and port.</li>
</ul>
<h2>How to draw it in Archboard, step by step</h2>
<p>Archboard's Kubernetes pack has 33 first-class node types with ports, from Namespace (drawn as a frame), Node, Pod, Deployment, StatefulSet, Job and CronJob to Service, Ingress, Gateway API routes, ConfigMap, Secret, PersistentVolumeClaim, HPA, NetworkPolicy and RBAC. You connect ports instead of drawing loose lines between generic shapes. You can start from your manifests with <strong>Import from YAML…</strong> or place each node by hand; either way, the "what matters here?" decision this guide is about stays yours.</p>
<ol>
<li><strong>Study the examples.</strong> Open <a href="https://getarchboard.app/examples/kubernetes-microservices">the Kubernetes microservices example</a> (Ingress → Service → Deployment/Pod → PVC → Postgres) and <a href="https://getarchboard.app/examples/kubernetes-ingress-flow">the Ingress flow example</a>. Note the layout: traffic flows one way and state sits at the end.</li>
<li><strong>Create a diagram</strong> in your workspace and add a Frame for the cluster, named after the cluster and environment.</li>
<li><strong>Add a Namespace</strong> for each namespace that matters, inside the cluster frame.</li>
<li><strong>Place the request path:</strong> Ingress, then Service, then Deployment, left to right. Connect port to port and add short Text labels for host/path and ports.</li>
<li><strong>Attach config and state:</strong> ConfigMap and Secret next to the Deployment that reads them, a PVC for persistent storage, and a database node outside the cluster frame for a managed Postgres.</li>
<li><strong>Add scaling and policy:</strong> an HPA beside its Deployment with min/max and metric, and NetworkPolicy nodes at the namespace boundaries they protect.</li>
<li><strong>Add context on the canvas:</strong> a Markdown block with owner, last-checked date and links to the repo or runbook. Code blocks work on the canvas too, so the key manifest excerpt can sit next to its nodes.</li>
<li><strong>Share it:</strong> export SVG or PNG for a design doc, or share a public link. Autosave and revision snapshots let you step back if a rework goes wrong.</li>
</ol>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/kmtrhgzy39ozs18gtn0t.png" alt="Kubernetes cluster diagram: users reach an Ingress that routes to the web and api Services and Deployments; an HPA scales web; api reads a ConfigMap and a Secret, queries a search StatefulSet with a PVC and connects to managed Postgres outside the cluster; a NetworkPolicy restricts access to api." /></p>
<p><em>A Kubernetes architecture diagram that shows traffic, boundaries and state: namespace, workloads, config, storage, policy and the managed database outside the cluster.</em></p>
<p>For a multi-account view of several clusters, the Cloud pack has a Kubernetes Cluster node.</p>
<p>The Free plan includes every built-in pack and allows 15 diagram nodes per diagram, plus 150 notes and text, which fits one service's request path. A full multi-service map will likely need Pro.</p>
<h2>The free template</h2>
<p>The free template is <a href="https://getarchboard.app/templates/kubernetes-architecture">Kubernetes cluster architecture template</a>: <strong>Use this template</strong> opens it as a new diagram in your workspace. For a fuller layout, <a href="https://getarchboard.app/examples/kubernetes-microservices">Kubernetes Microservices: example diagram</a> has <strong>Use this example</strong>, which copies it so you can rename the nodes to your services. For the traffic path alone, <a href="https://getarchboard.app/examples/kubernetes-ingress-flow">Kubernetes Ingress Flow: example diagram</a> is a smaller starting point. More patterns are on the <a href="https://getarchboard.app/use-cases/kubernetes">Kubernetes use-case page</a>.</p>
<h2>FAQ</h2>
<p><strong>Should I draw the control plane?</strong> Only if the diagram is about the platform itself, for example for a platform team or an upgrade plan. In application diagrams the control plane is noise; readers assume it exists.</p>
<p><strong>Pods or Deployments?</strong> Deployments, with a replica count. Draw individual Pods only when a specific Pod matters: a sidecar layout, a debugging session, or a Job or CronJob run.</p>
<p><strong>How do I keep it current?</strong> Give it an owner, put a last-checked date on the canvas, and review it alongside the pull requests that change the services it shows. A JSON export of the diagram can live in the repo next to the manifests.</p>
<p><strong>Can one diagram cover several clusters?</strong> Yes, at a higher level: one boundary per cluster, with only cross-cluster traffic drawn. Keep per-cluster detail in separate diagrams.</p>
<hr />
<p><em>This post was originally published on the <a href="https://getarchboard.app/blog/kubernetes-architecture-diagram">Archboard blog</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Saga Pattern Diagram: Orchestration vs Choreography]]></title><description><![CDATA[The saga pattern explained with a diagram: local transactions, compensations, pivot and retryable steps, orchestration vs choreography and isolation.]]></description><link>https://archboard.hashnode.dev/saga-pattern-diagram-orchestration-vs-choreography</link><guid isPermaLink="true">https://archboard.hashnode.dev/saga-pattern-diagram-orchestration-vs-choreography</guid><category><![CDATA[Microservices]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Halil Öncen]]></dc:creator><pubDate>Sun, 22 Nov 2026 11:50:16 GMT</pubDate><content:encoded><![CDATA[<p>Placing an order touches three services: inventory reserves stock, payments authorizes the card, shipping creates a shipment. In a monolith that is one database transaction. Split into services with their own databases, there is no transaction that spans all three, and two-phase commit across services is rarely an option in practice.</p>
<p>The saga pattern is the standard answer. This post explains how a saga works, the difference between orchestration and choreography, how compensations and pivot steps fit together, and the isolation problems sagas do not solve for you. The diagram shows an orchestrated order saga.</p>
<h2>What a saga is</h2>
<p>A saga is a sequence of local transactions. Each step commits in its own service's database and triggers the next. If a step fails, the saga runs <strong>compensating transactions</strong> that undo the effects of the steps that already committed.</p>
<p>The idea is older than microservices: Hector Garcia-Molina and Kenneth Salem described sagas in a 1987 paper about long-lived database transactions. The pattern came back because service boundaries recreated the same problem.</p>
<p>Two consequences shape everything else:</p>
<ul>
<li><strong>Eventual consistency.</strong> Between the first and last step, the system is in an intermediate state that other requests can see. The order is PENDING, the stock is reserved, the card is authorized but not captured.</li>
<li><strong>Compensation is not rollback.</strong> You cannot un-send an email or un-charge a card silently. A compensation is a new business action, such as voiding an authorization or issuing a refund, that semantically reverses the earlier one.</li>
</ul>
<h2>Compensable, pivot and retryable steps</h2>
<p>Classify every step before drawing anything. The <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/saga">Azure Architecture Center's saga pattern guide</a> uses three kinds:</p>
<table>
<thead>
<tr>
<th>Kind</th>
<th>Meaning</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td>Compensable</td>
<td>Can be undone by another transaction</td>
<td>Reserve stock; authorize payment</td>
</tr>
<tr>
<td>Pivot</td>
<td>The point of no return: once it succeeds, the saga must finish</td>
<td>Create the shipment</td>
</tr>
<tr>
<td>Retryable</td>
<td>Comes after the pivot and must eventually succeed; idempotent</td>
<td>Send the confirmation email</td>
</tr>
</tbody></table>
<p>Order matters. Put compensable steps first, the pivot next, and only retryable steps after it. If the pivot fails, compensate; once it succeeds, retry everything after it until it succeeds. A saga with a compensable step after the pivot cannot reach a consistent state when that step fails.</p>
<h2>Orchestration vs choreography</h2>
<p>There are two ways to coordinate the steps.</p>
<p><strong>Orchestration:</strong> a saga orchestrator, often a state machine with durable state, tells each service what to do and waits for the reply. It owns the sequence, the retries, the timeouts and the compensations.</p>
<p><strong>Choreography:</strong> there is no coordinator. Each service listens for events and reacts: inventory hears OrderCreated and reserves stock, payments hears StockReserved and authorizes, and so on. Failures are events too, and each service knows which compensation to run.</p>
<table>
<thead>
<tr>
<th></th>
<th>Orchestration</th>
<th>Choreography</th>
</tr>
</thead>
<tbody><tr>
<td>Where the flow lives</td>
<td>One place: the orchestrator</td>
<td>Spread across services' event handlers</td>
</tr>
<tr>
<td>Adding a step</td>
<td>Change the orchestrator</td>
<td>Change who listens to which event</td>
</tr>
<tr>
<td>Seeing the state of one order</td>
<td>Query the saga log</td>
<td>Reconstruct it from events</td>
</tr>
<tr>
<td>Coupling</td>
<td>Services know the orchestrator's commands</td>
<td>Services know each other's events</td>
</tr>
<tr>
<td>Good fit</td>
<td>Many steps, branching, strict ordering</td>
<td>Two or three steps, simple flows</td>
</tr>
</tbody></table>
<p>Choreography is pleasant for short flows and painful when someone asks "why is order 8812 stuck?". Orchestration gives that question one place to look. Workflow engines such as Temporal, AWS Step Functions or Camunda provide durable orchestration so you do not build the state machine yourself. Chris Richardson's <a href="https://microservices.io/patterns/data/saga.html">saga pattern page</a> has worked examples of both styles.</p>
<h2>Isolation: the part sagas leave to you</h2>
<p>A database transaction hides intermediate state from other transactions. A saga does not. While an order saga is running, another request can read the reserved stock, or a second saga can modify the same record. The usual countermeasures:</p>
<ul>
<li><strong>Semantic lock.</strong> Mark records as in progress (an order in PENDING, stock in RESERVED) so other operations know to wait or refuse.</li>
<li><strong>Commutative updates.</strong> Design operations so they give the same result in any order, such as incrementing and decrementing counts instead of setting them.</li>
<li><strong>Reread before writing.</strong> Check that a value has not changed since the saga read it, and fail or restart if it has.</li>
</ul>
<p>Make every step and every compensation idempotent, keyed by the saga ID and step. Messages will be delivered twice, and a retried "void authorization" must not void a different payment.</p>
<h2>Timeouts and stuck sagas</h2>
<p>Every step needs a deadline. A payment service that never answers leaves the saga waiting forever and the stock reserved. Give each step a timeout, treat a timeout as a failure before the pivot (compensate) and as a reason to retry after it, and alert on sagas that stay in one state longer than expected. A small dashboard of sagas by current step answers most support questions on its own. Record why each saga ended, too.</p>
<h2>The architecture diagram</h2>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/2g9uwvqiscj31alfrrsq.png" alt="An order service starts a saga in an orchestrator that logs each step and calls inventory, payment and shipping services in order. A decision checks whether all steps succeeded: yes leads to order approved, no leads to compensation in reverse order and order rejected." /></p>
<p><em>An order saga run by an orchestrator. It reserves stock, authorizes payment and creates the shipment as local transactions, persists every step, and if a step before the pivot fails it compensates the earlier steps in reverse order.</em></p>
<p>How to read it:</p>
<ul>
<li><strong>Left:</strong> the order service creates the order in PENDING and starts the saga.</li>
<li><strong>Middle:</strong> the orchestrator runs the steps in order and persists each one to the saga log, so a restart resumes where it stopped.</li>
<li><strong>Right:</strong> the three services, each labeled with its step number and kind. Inventory and payment are compensable; shipping is the pivot.</li>
<li><strong>Bottom:</strong> if all steps succeed the order becomes APPROVED. If a step before the pivot fails, the orchestrator compensates in reverse order (void the authorization, then release the stock) and the order becomes REJECTED.</li>
<li><strong>The Markdown table</strong> pairs every action with its compensation, which is the first thing a reviewer should check.</li>
</ul>
<h2>What to put on a saga diagram</h2>
<ul>
<li><strong>The step order and each step's kind.</strong> Compensable, pivot or retryable belongs on the box.</li>
<li><strong>Every compensation.</strong> A step without one is either the pivot, retryable, or a bug.</li>
<li><strong>Where saga state lives.</strong> A saga that cannot survive a crash halfway through is not finished.</li>
<li><strong>The visible intermediate states.</strong> PENDING and RESERVED are part of the design; other features will see them.</li>
</ul>
<p>Sagas pair naturally with the <a href="https://getarchboard.app/blog/transactional-outbox-pattern">transactional outbox pattern</a>, because each step must update its database and send a message without losing either. The <a href="https://getarchboard.app/blog/microservices-architecture-diagram">microservices architecture diagram</a> shows where these services sit, and the <a href="https://getarchboard.app/blog/payment-gateway-integration-diagram">payment gateway integration diagram</a> covers the authorization and capture steps in detail.</p>
<h2>Build it in Archboard</h2>
<ol>
<li>Sign in with Google or GitHub and create a diagram.</li>
<li>Add <strong>Container</strong> nodes from the <strong>C4 Model</strong> pack for the order service, the saga orchestrator and the three participating services, and a <strong>Database</strong> for the saga log.</li>
<li>Put the step number and kind (compensable or pivot) in each service's technology field.</li>
<li>Add a <strong>Decision</strong>, a <strong>Process</strong> and two <strong>Terminator</strong> nodes from the <strong>Flowchart</strong> pack for the success and compensation paths.</li>
<li>Add a <strong>Markdown</strong> block from the <strong>Core</strong> pack with a table of actions and compensations.</li>
</ol>
<p>The example uses 11 diagram nodes, within the Free plan.</p>
<h2>FAQ</h2>
<p><strong>What is the difference between a saga and a distributed transaction?</strong> A distributed transaction (two-phase commit) locks resources across databases until everyone commits. A saga commits each step locally and undoes earlier steps with compensations if a later one fails, trading isolation for availability.</p>
<p><strong>Should I use orchestration or choreography?</strong> Orchestration for flows with many steps, branches or strict ordering, because the state of each saga lives in one place. Choreography for short flows where two or three services react to each other's events.</p>
<p><strong>What is a pivot transaction?</strong> The step after which the saga can no longer be compensated. Everything before it must be compensable; everything after it must be retryable until it succeeds.</p>
<p><strong>How do I handle failures in a compensation?</strong> Retry it. Compensations must be idempotent and eventually succeed; if one cannot, the saga needs a manual resolution path and an alert.</p>
<p><strong>Do sagas give me isolation?</strong> No. Other requests can see intermediate states. Use semantic locks such as PENDING states, commutative updates and rereads to prevent the anomalies that matter to your business.</p>
<hr />
<p><em>This post was originally published on the <a href="https://getarchboard.app/blog/saga-pattern-diagram">Archboard blog</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[RAG Architecture Diagram: How a Retrieval-Augmented Generation App Fits Together]]></title><description><![CDATA[Draw a RAG architecture diagram with both paths: chunking and embeddings, then retrieval, permissions, reranking, prompt assembly and evaluation.]]></description><link>https://archboard.hashnode.dev/rag-architecture-diagram-how-a-retrieval-augmented-generation-app-fits-together</link><guid isPermaLink="true">https://archboard.hashnode.dev/rag-architecture-diagram-how-a-retrieval-augmented-generation-app-fits-together</guid><category><![CDATA[RAG ]]></category><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[llm]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Halil Öncen]]></dc:creator><pubDate>Sat, 21 Nov 2026 11:49:30 GMT</pubDate><content:encoded><![CDATA[<p>Most RAG architecture diagrams have three boxes: a user, a vector database and an LLM. That picture explains the idea in a meeting. It does not help anyone run the system, because the decisions that decide answer quality and safety are not on it: how documents are chunked, which embedding model is used, who may see which chunk, how results are ranked, and how anyone knows the answers are good.</p>
<p>This guide draws the full picture of a retrieval-augmented generation app as two paths around shared models and stores, then covers what to label and the mistakes that show up most often.</p>
<h2>Two paths, not one</h2>
<p>The term comes from <a href="https://arxiv.org/abs/2005.11401">Lewis et al. (2020)</a>, who combined a language model with a dense vector index of Wikipedia that a retriever searched at generation time. Most production RAG apps keep the idea without training the parts together: retrieve relevant passages, put them in the prompt, and ask the model to answer from them.</p>
<p>That gives every RAG app two paths:</p>
<ul>
<li><strong>Ingestion</strong> runs continuously in the background. It turns documents into chunks, vectors and metadata.</li>
<li><strong>Query</strong> runs once per question. It turns a question into an answer with sources.</li>
</ul>
<p>They meet at the shared parts: the embedding model, which must be the same version on both paths, the vector index and the metadata store. A diagram that shows only the query path hides half the system and most of the bugs.</p>
<h2>The ingestion path</h2>
<ol>
<li><strong>Sources and change detection.</strong> Connectors, webhooks or a crawler notice new, changed and deleted documents and put jobs on a queue. Deletions and permission changes are jobs too.</li>
<li><strong>Parsing.</strong> Extract text while keeping structure: headings, lists, tables, and metadata such as title, URL, owner, last update and access control list.</li>
<li><strong>Chunking.</strong> Split along the document's structure first, then by size. Chunk size and overlap are parameters you tune against your own questions, not universal numbers. Keep the heading path in each chunk so a paragraph still makes sense on its own.</li>
<li><strong>Embedding.</strong> Call one embedding model and pin its version. Store the model name and version with every vector. Vectors from different models are not comparable, so changing the model means re-embedding the whole corpus.</li>
<li><strong>Indexing.</strong> Upsert each chunk with its vector, document ID, chunk number, version and access tags. Keep a keyword index next to the vector index if you plan hybrid search.</li>
<li><strong>Refresh and deletion.</strong> Make upserts idempotent, delete the chunks of removed documents, and track freshness: how long a change in the source takes to reach the index.</li>
</ol>
<h2>The query path</h2>
<ol>
<li><strong>Identify the user.</strong> Resolve the user's groups before retrieval starts.</li>
<li><strong>Rewrite the question (optional).</strong> A follow-up such as "and for contractors?" needs the conversation to become a standalone query.</li>
<li><strong>Retrieve.</strong> Vector search finds passages with similar meaning; keyword search finds exact terms such as error codes and product names. Hybrid search runs both and merges the lists, often with reciprocal rank fusion, which scores each document by 1/(k + rank) summed over the lists. The <a href="https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf">original RRF paper</a> fixed k at 60.</li>
<li><strong>Filter by permission inside the query.</strong> Pass the user's groups as a filter on the access tags, so chunks the user may not see never reach the prompt. Check how your store applies filters. pgvector's documentation notes that with approximate indexes the filter runs after the index scan: with HNSW's default <code>ef_search</code> of 40, a filter that matches 10% of rows returns about 4 rows on average. Iterative scans, partial indexes or partitioning fix that.</li>
<li><strong>Rerank.</strong> Retrieve generously, for example 50 candidates, and let a reranking model score them against the question. Keep the best few, for example 8.</li>
<li><strong>Assemble the prompt.</strong> Instructions, the selected chunks with IDs and titles, and the question, inside a token budget. Ask for citations by chunk ID.</li>
<li><strong>Generate and cite.</strong> Call the LLM, stream the answer and turn chunk IDs into links the user can check.</li>
</ol>
<h2>Around both paths</h2>
<ul>
<li><strong>Treat retrieved text as untrusted input.</strong> A document can contain instructions aimed at the model. OWASP lists this as <a href="https://genai.owasp.org/llmrisk/llm01-prompt-injection/">indirect prompt injection</a>. Keep tools and data the model can reach as narrow as the user's own access.</li>
<li><strong>Trace every request.</strong> Log the rewritten query, the retrieved and reranked chunk IDs with scores, the prompt version, the model versions and the latency of each step.</li>
<li><strong>Evaluate on a fixed question set.</strong> Run it on every change to chunking, models, retrieval or the prompt. The <a href="https://arxiv.org/abs/2309.15217">RAGAS paper</a> names three useful dimensions: faithfulness to the retrieved context, answer relevance and context relevance. Also check whether the expected source appears in the top results.</li>
<li><strong>Cache with care.</strong> Caching query embeddings is usually safe. Caching answers is only safe per permission set.</li>
</ul>
<h2>The diagram</h2>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/61fyu4o6hcr5o5aevyci.png" alt="RAG architecture diagram. Left, the ingestion path: source documents, an ingestion jobs queue and an ingestion worker. Center: an embedding model, a vector index, Postgres for metadata and permissions, and the LLM. Right, the query path: the user, the RAG API and a reranker." /></p>
<p><em>A retrieval-augmented generation app with both paths: ingestion turns documents into permission-tagged chunks and vectors, and each question goes through hybrid search, permission filtering, reranking and a prompt with sources.</em></p>
<p>How to read it:</p>
<ul>
<li><strong>Left, ingestion.</strong> Source changes become jobs on a queue. The ingestion worker parses and chunks each document, calls the embedding model, upserts chunks and vectors with access tags into the vector index, and writes document metadata to Postgres.</li>
<li><strong>Center, shared models and stores.</strong> The same pinned embedding model serves both paths. The LLM sits here too, called only by the query path.</li>
<li><strong>Right, query.</strong> The RAG API looks up the user's groups, embeds the question, runs hybrid search with the permission filter, sends 50 candidates to the reranker, and calls the LLM with the best 8 chunks.</li>
<li><strong>Bottom left.</strong> An example latency budget per step, so a slow answer can be traced to the step that broke its budget.</li>
</ul>
<h2>What to label</h2>
<ul>
<li><strong>Model versions</strong> on every model node, including the embedding model.</li>
<li><strong>Chunking parameters</strong> on the ingestion worker or in a note.</li>
<li><strong>Where permissions are enforced</strong>, on the retrieval edge, not in a footnote.</li>
<li><strong>How many results flow</strong> between steps: 50 retrieved, 8 in the prompt.</li>
<li><strong>Freshness and latency targets:</strong> how fast a source change is searchable, and the budget per query step.</li>
</ul>
<h2>Common mistakes</h2>
<ul>
<li><strong>One box called "AI".</strong> Retrieval, reranking and generation fail in different ways and need separate boxes.</li>
<li><strong>No ingestion path.</strong> Stale or missing answers often start there.</li>
<li><strong>No permissions.</strong> If the index holds documents with different audiences, a diagram without access tags describes a data leak.</li>
<li><strong>No evaluation.</strong> Without a question set, every change to the prompt or chunk size is a guess.</li>
<li><strong>Mixed embedding versions.</strong> Re-embedding half the corpus with a new model quietly breaks search.</li>
</ul>
<h2>When RAG is not the answer</h2>
<ul>
<li><strong>The answer lives in structured data.</strong> Query the database or an API instead of embedding table rows.</li>
<li><strong>The task needs a whole document.</strong> Summarizing one contract works better with the full contract in the prompt, if it fits.</li>
<li><strong>The corpus is tiny.</strong> A few pages can go straight into the prompt.</li>
<li><strong>You need different behavior, not more knowledge.</strong> That is a prompt or fine-tuning problem.</li>
</ul>
<p>For event-driven ingestion with queues, see the <a href="https://getarchboard.app/blog/event-driven-architecture-diagram">event-driven architecture diagram</a> guide.</p>
<h2>Build it in Archboard</h2>
<ol>
<li>Sign in with Google or GitHub and create a diagram.</li>
<li>Add two Core <strong>Frame</strong> nodes, "Ingestion path" on the left and "Query path" on the right.</li>
<li>In the ingestion frame, add a Data pack <strong>Object Store</strong> for source documents, a Data pack <strong>Queue</strong> for ingestion jobs and a C4 Model <strong>Container</strong> for the ingestion worker.</li>
<li>In the center, add an ML pack <strong>Model</strong> for the embedding model, an ML pack <strong>Vector index</strong>, a Data pack <strong>Postgres</strong> for metadata and permissions, and a second <strong>Model</strong> for the LLM.</li>
<li>In the query frame, add a C4 Model <strong>Person</strong> for the user, a <strong>Container</strong> for the RAG API and an ML pack <strong>Model</strong> for the reranker.</li>
<li>Label each edge with what flows, including "top 50" and "top 8", and put the latency budget in a Core <strong>Markdown</strong> block.</li>
</ol>
<p>The example uses 13 diagram nodes, within the Free plan. If you work with an AI agent, it can draw a first version for you over MCP from a description of both paths; see <a href="https://getarchboard.app/blog/ai-agents-architecture-diagrams-mcp">how to create architecture diagrams with AI agents</a>. For the general method, see <a href="https://getarchboard.app/blog/how-to-draw-software-architecture-diagram">how to draw a software architecture diagram</a>.</p>
<h2>FAQ</h2>
<p><strong>Do I need a dedicated vector database for RAG?</strong> No. A vector extension in a database you already run, such as pgvector in PostgreSQL, or a search engine with vector support works for many apps. Choose by corpus size, filtering needs and what your team operates well.</p>
<p><strong>What chunk size should I use?</strong> There is no universal number. Split along headings and paragraphs, then compare a few sizes and overlaps on your own question set.</p>
<p><strong>Where should permission checks happen?</strong> At ingestion, by copying each document's access list into its chunks, and at retrieval, by filtering on it. Never rely on the prompt to hide content.</p>
<p><strong>How do I evaluate a RAG app?</strong> Keep a fixed set of real questions with expected sources. Measure whether retrieval finds those sources, and whether answers are faithful to the retrieved context and relevant to the question.</p>
<p><strong>Should the LLM call tools instead of using RAG?</strong> For live or structured data, yes: a tool that queries the system of record beats an index of copies. Many apps use both.</p>
<hr />
<p><em>This post was originally published on the <a href="https://getarchboard.app/blog/rag-architecture-diagram">Archboard blog</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[URL Shortener System Design: Architecture Diagram and Trade-offs]]></title><description><![CDATA[A URL shortener system design with real numbers: base62 codes, ID ranges vs hashing, 301 vs 302, caching, analytics and a full diagram.]]></description><link>https://archboard.hashnode.dev/url-shortener-system-design-architecture-diagram-and-trade-offs</link><guid isPermaLink="true">https://archboard.hashnode.dev/url-shortener-system-design-architecture-diagram-and-trade-offs</guid><category><![CDATA[System Design]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Halil Öncen]]></dc:creator><pubDate>Fri, 20 Nov 2026 11:47:48 GMT</pubDate><content:encoded><![CDATA[<p>A URL shortener looks like a weekend project: take a long URL, hand back a short code, redirect when someone clicks it. That is why it shows up in so many system design interviews. The small surface hides real decisions about ID generation, caching, HTTP semantics and analytics, and each one changes the architecture.</p>
<p>This post designs one end to end. It starts with the numbers, walks through how to generate short codes without collisions, settles the 301 versus 302 question, and ends with an architecture diagram you can copy and adapt.</p>
<h2>Requirements and numbers</h2>
<p>Functional requirements:</p>
<ul>
<li>Create a short link for a long URL, optionally with a custom alias.</li>
<li>Redirect a short link to its long URL.</li>
<li>Count clicks per link.</li>
<li>Expire links when asked to.</li>
</ul>
<p>Non-functional requirements: redirects must be fast and highly available, short codes must not be guessable in sequence if links can be private, and the system must not become a free redirector for phishing pages.</p>
<p>Back-of-envelope numbers make the shape obvious:</p>
<table>
<thead>
<tr>
<th>Assumption</th>
<th>Value</th>
<th>Per second</th>
</tr>
</thead>
<tbody><tr>
<td>New links per month</td>
<td>100 million</td>
<td>about 40 writes/s</td>
</tr>
<tr>
<td>Redirects per month</td>
<td>10 billion</td>
<td>about 3,900 reads/s</td>
</tr>
<tr>
<td>Read to write ratio</td>
<td>100:1</td>
<td></td>
</tr>
<tr>
<td>Record size</td>
<td>about 500 bytes</td>
<td></td>
</tr>
<tr>
<td>Storage for 5 years</td>
<td>6 billion links</td>
<td>about 3 TB</td>
</tr>
</tbody></table>
<p>Reads outnumber writes by two orders of magnitude, so the read path gets the cache, the replicas and the attention. The write path is small and can be simple.</p>
<h2>The API</h2>
<p>Two endpoints carry the product:</p>
<pre><code class="language-http">POST /links
Content-Type: application/json

{"url": "https://example.com/very/long/path", "alias": "launch", "expiresAt": "2027-01-01T00:00:00Z"}

201 Created
{"code": "launch", "shortUrl": "https://sho.rt/launch"}

GET /launch

302 Found
Location: https://example.com/very/long/path
</code></pre>
<p>Keep them on separate services. The redirect service is stateless and read-only, so you can scale it on its own and deploy it rarely.</p>
<h2>Generating the short code</h2>
<p>The short code is a number written in base62 (a–z, A–Z, 0–9). Seven characters give 62^7, about 3.5 trillion codes; six give about 56.8 billion. At 100 million links a month, seven characters last for thousands of years.</p>
<p>The real question is where the number comes from:</p>
<table>
<thead>
<tr>
<th>Approach</th>
<th>How it works</th>
<th>Watch out for</th>
</tr>
</thead>
<tbody><tr>
<td>Counter + base62</td>
<td>One global sequence, encoded</td>
<td>Single point of contention; codes are sequential and guessable</td>
</tr>
<tr>
<td>ID ranges</td>
<td>An allocator hands each API instance a block of IDs (say 100,000)</td>
<td>Gaps when an instance dies; still sequential within a block</td>
</tr>
<tr>
<td>Hash + truncate</td>
<td>Hash the URL, keep the first 7 base62 characters</td>
<td>Collisions; you need a check-and-retry</td>
</tr>
<tr>
<td>Snowflake-style IDs</td>
<td>Timestamp + machine ID + sequence in 64 bits</td>
<td>Longer codes (11 characters in base62)</td>
</tr>
</tbody></table>
<p>Hashing is tempting because the same URL always gets the same code. The catch is the birthday problem: with 3.5 trillion possible codes, the chance of at least one collision passes 50% after only about 2.2 million links. Every insert then needs a uniqueness check and a retry with a salt, which turns a write into a read plus a write.</p>
<p>ID ranges are the pragmatic default. Each API instance reserves a block from the allocator in one small transaction, then hands out codes from memory with no coordination. If you do not want sequential codes, run the ID through a reversible permutation (a block cipher over the ID space, for example) before encoding it. Twitter's <a href="https://github.com/twitter-archive/snowflake">Snowflake</a> shows the other route: a 41-bit timestamp, a 10-bit machine ID and a 12-bit sequence give unique 64-bit IDs without any central allocator, at the cost of longer codes.</p>
<p>Custom aliases skip the generator. Store them in the same table and rely on a unique constraint on the code column to reject duplicates.</p>
<h2>301 or 302?</h2>
<p><a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-redirection-3xx">RFC 9110</a> defines the redirect codes. The difference that matters here is caching: a 301 (Moved Permanently) response is heuristically cacheable, so browsers can remember it and skip your server on the next click. A 302 (Found) is temporary and is not cached unless you say so.</p>
<ul>
<li>Use <strong>302</strong> when you need every click counted or want to change the target later.</li>
<li>Use <strong>301</strong> when the link never changes and you prefer fewer requests over complete analytics.</li>
</ul>
<p>307 and 308 are the method-preserving versions of 302 and 301. For plain browser clicks, which are GET requests, the choice between them rarely matters.</p>
<h2>Storage and caching</h2>
<p>Every redirect is a point lookup by code, so any store that does fast key lookups works: a key-value store such as DynamoDB or Cassandra, or Postgres with the code as the primary key. Shard by the code when one node is no longer enough; a hash of the code spreads load evenly because no code is hotter than another by design. Hot links are the exception, and the cache absorbs them.</p>
<p>Put a Redis cache in front of the store with a cache-aside read: look up the code in Redis, fall back to the database on a miss, then fill the cache with a TTL. Link popularity follows a long tail, so a cache holding a small fraction of links serves most clicks. The <a href="https://getarchboard.app/blog/caching-strategies-diagram">caching strategies post</a> covers TTLs, stampedes and invalidation in detail. Read replicas help the fallback path; the <a href="https://getarchboard.app/blog/database-replication-diagram">database replication post</a> explains the lag you then have to tolerate.</p>
<p>A CDN or edge cache can serve the most popular redirects directly if you send a Cache-Control header, but the edge then answers clicks your servers never see. Either log at the edge or keep redirects uncached.</p>
<h2>Click analytics without slowing the redirect</h2>
<p>Never write a click count synchronously on the redirect path. The redirect service publishes a small click event (code, timestamp, referrer, country) to a log such as Kafka and returns immediately. A consumer aggregates counts per link per day and writes them to an analytics store. If the analytics side falls behind, redirects keep working; it is the same decoupling described in the <a href="https://getarchboard.app/blog/event-driven-architecture-diagram">event-driven architecture post</a>.</p>
<h2>The architecture diagram</h2>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/y1a3x7d8h96zpr78zkdh.png" alt="A user reaches a CDN and load balancer. GET requests go to a redirect service that reads Redis, then a links store on a miss. POST requests go to a shorten API that takes ID ranges from an allocator, checks URLs with a reputation API and writes links. Clicks go via Kafka to analytics." /></p>
<p><em>A URL shortener with separate read and write paths. Redirects hit a cache first, new links get IDs from pre-allocated ranges, and click events flow to analytics without slowing the redirect.</em></p>
<p>How to read it:</p>
<ul>
<li><strong>Read path (top).</strong> Requests for <code>GET /{code}</code> pass the edge and the load balancer to the redirect service, which checks Redis first and the links store only on a miss.</li>
<li><strong>Write path (bottom).</strong> <code>POST /links</code> goes to the shorten API. It checks the target with a URL reputation service, takes IDs from a range it reserved from the allocator, encodes them in base62 and writes the link.</li>
<li><strong>Analytics (right).</strong> Click events are dashed because they are asynchronous. The aggregator turns them into daily counts.</li>
<li><strong>The Markdown block</strong> keeps the capacity numbers next to the design, so a reviewer can check them.</li>
</ul>
<h2>Abuse, expiry and custom aliases</h2>
<p>A public shortener is a phishing tool unless you stop it. Check new targets against a reputation service such as <a href="https://developers.google.com/safe-browsing">Google Safe Browsing</a>, rate-limit link creation per account and IP, and keep a way to disable a code quickly. Recheck old links periodically, because a clean domain can turn malicious later.</p>
<p>For expiry, store <code>expiresAt</code> with the link and check it on redirect, then delete expired rows with a background job. Return 404 or 410 for expired codes instead of redirecting.</p>
<h2>What to put on the diagram</h2>
<ul>
<li><strong>Separate the read and write paths.</strong> They scale differently, and the diagram should show it.</li>
<li><strong>Label the redirect status</strong> (301 or 302) on the redirect service. It decides whether analytics is complete.</li>
<li><strong>Show where IDs come from.</strong> "Generate code" in a box hides the most discussed decision in the design.</li>
<li><strong>Mark asynchronous flows as dashed.</strong> Readers should see at a glance that analytics cannot slow a redirect.</li>
<li><strong>Write the numbers down.</strong> A design without writes per second and storage size cannot be reviewed.</li>
</ul>
<p>The <a href="https://getarchboard.app/blog/system-design-diagram-example">system design diagram example</a> shows the same conventions on a larger system.</p>
<h2>Build it in Archboard</h2>
<ol>
<li>Sign in with Google or GitHub and create a diagram.</li>
<li>Add a <strong>Person</strong> from the <strong>C4 Model</strong> pack for the user, a <strong>CDN</strong> and a <strong>Cloud LB</strong> from the <strong>Cloud</strong> pack.</li>
<li>Add four <strong>Container</strong> nodes from the <strong>C4 Model</strong> pack: the redirect service, the shorten API, the ID allocator and the click aggregator. Put the technology and a one-line description on each.</li>
<li>Add <strong>Redis</strong>, <strong>Kafka</strong> and a <strong>Data Warehouse</strong> from the <strong>Data</strong> pack, a <strong>Database</strong> from the <strong>C4 Model</strong> pack for the links store and an <strong>External System</strong> for the URL reputation API.</li>
<li>Connect the read path at the top and the write path at the bottom, draw the click events as dashed edges, and add a <strong>Markdown</strong> block from the <strong>Core</strong> pack with the capacity numbers.</li>
</ol>
<p>The example uses 13 diagram nodes, within the Free plan.</p>
<h2>FAQ</h2>
<p><strong>How long should a short code be?</strong> Seven base62 characters give about 3.5 trillion codes, enough for decades at 100 million links a month. Start with seven and let codes grow to eight later; nothing in the design depends on a fixed length.</p>
<p><strong>Should I hash the long URL to get the code?</strong> Only if deduplication matters more than simple writes. Truncated hashes collide early (past 2.2 million links for 7 characters there is a better than even chance of at least one collision), so every insert needs a check and a retry.</p>
<p><strong>Is a 301 or a 302 better for a URL shortener?</strong> A 302 if you need every click counted or may change the target. A 301 lets browsers cache the redirect, which saves requests but hides repeat clicks from your analytics.</p>
<p><strong>Which database should store the links?</strong> Any store with fast lookups by primary key. Postgres is enough for a long time at these numbers; a key-value store becomes attractive when you need to shard writes across many nodes.</p>
<p><strong>How do I stop people from guessing links?</strong> Do not expose sequential IDs. Permute the ID before encoding it, or use random codes with a uniqueness check, and never treat a short link as a secret for private content.</p>
<hr />
<p><em>This post was originally published on the <a href="https://getarchboard.app/blog/url-shortener-system-design">Archboard blog</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Clean Architecture Diagram: Layers, the Dependency Rule and a Worked Example]]></title><description><![CDATA[One use case traced through the four clean architecture layers: the dependency rule, code, folders and how to draw the diagram.]]></description><link>https://archboard.hashnode.dev/clean-architecture-diagram-layers-the-dependency-rule-and-a-worked-example</link><guid isPermaLink="true">https://archboard.hashnode.dev/clean-architecture-diagram-layers-the-dependency-rule-and-a-worked-example</guid><category><![CDATA[software architecture]]></category><category><![CDATA[Clean Architecture]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Halil Öncen]]></dc:creator><pubDate>Thu, 19 Nov 2026 10:43:09 GMT</pubDate><content:encoded><![CDATA[<p>Most engineers have seen the clean architecture picture: four colored rings with arrows pointing at the middle. Far fewer can say what goes into each ring for a real feature, which way the imports should point, or where the SQL lives.</p>
<p>The gap shows up in code review: a <code>domain</code> folder that imports the ORM, a use case that returns an HTTP status code, five mappers between a form and a table.</p>
<p>This post turns Robert C. Martin's circles into a component diagram for one use case, placing an order: the layers, the dependency rule, code and folders, boundary crossings, clean versus hexagonal and onion, mistakes, when it is overkill, and how to draw it.</p>
<h2>The four layers</h2>
<p>Martin described the clean architecture in a 2012 blog post, <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">The Clean Architecture</a>, and expanded it in his 2017 book <em>Clean Architecture</em>. He presented it as an integration of earlier ideas, including hexagonal and onion architecture. From the center outward:</p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>What it holds</th>
<th>In the example</th>
<th>Changes when</th>
</tr>
</thead>
<tbody><tr>
<td>Entities</td>
<td>Enterprise business rules, reusable across applications</td>
<td><code>Order</code> and its rule that an order needs at least one line</td>
<td>A business rule changes</td>
</tr>
<tr>
<td>Use cases</td>
<td>Application business rules, one workflow each</td>
<td><code>PlaceOrder</code>, its two interfaces, request and response models</td>
<td>The workflow changes</td>
</tr>
<tr>
<td>Interface adapters</td>
<td>Controllers, presenters, gateways and all the SQL</td>
<td><code>OrderController</code>, <code>OrderPresenter</code>, <code>PostgresOrderRepository</code></td>
<td>The API or the schema changes</td>
</tr>
<tr>
<td>Frameworks and drivers</td>
<td>Tools plus glue code: web framework, database, drivers</td>
<td>The HTTP framework, PostgreSQL, <code>pg</code>, <code>main.ts</code></td>
<td>You replace a tool</td>
</tr>
</tbody></table>
<p>The circles are schematic; Martin says you may need more than four. The rule connecting them never changes.</p>
<h2>The dependency rule</h2>
<p>In Martin's words, "source code dependencies can only point inwards." Code in an inner circle never mentions a function, class or variable declared in an outer one, or uses its data formats. For this example:</p>
<ul>
<li><code>entities</code> imports nothing from the other layers.</li>
<li><code>use-cases</code> imports only <code>entities</code>: no web framework, ORM or driver.</li>
<li><code>adapters</code> import inward, plus the library they adapt.</li>
<li>Only <code>main.ts</code> sees everything.</li>
</ul>
<p>The rule covers source code, not runtime calls: at runtime <code>PlaceOrder</code> calls outward, to the presenter and the database. Martin resolves this with the dependency inversion principle: the use case calls an interface it owns, and an outer class implements it. The call goes out; the dependency points in.</p>
<p>One dependency does point outward: the adapter imports the database driver. That is by design. Martin puts all SQL in the adapter layer, and no code inward of it "should know anything at all about the database."</p>
<p>Enforce the rule in CI with the <code>onionArchitecture()</code> check in <a href="https://www.archunit.org/userguide/html/000_Index.html">ArchUnit</a> on the JVM, dependency-cruiser for TypeScript or the layers contract of import-linter for Python.</p>
<h2>Worked example: placing an order</h2>
<p>A <code>POST /orders</code> request takes this path:</p>
<ol>
<li>The web framework routes it to <code>OrderController</code>.</li>
<li>The controller parses the body into a <code>PlaceOrderRequest</code>, a plain object owned by the use case layer, creates an <code>OrderPresenter</code> and calls <code>PlaceOrder.execute()</code>.</li>
<li><code>PlaceOrder</code> lets <code>Order.place()</code> apply the business rules, saves through <code>OrderRepository</code> and passes a <code>PlaceOrderResponse</code> to <code>PlaceOrderOutput</code>.</li>
<li><code>OrderPresenter</code> implements that interface and builds a view model: status 201, a <code>Location</code> header and a JSON body.</li>
<li>The controller returns the view model, and the framework writes it.</li>
</ol>
<p>The use case layer, with both interfaces it owns:</p>
<pre><code class="language-ts">// src/orders/use-cases/place-order.ts
import { Order } from '../entities/order';

export interface OrderRepository {             // implemented by an adapter
  nextId(): Promise&lt;string&gt;;
  save(order: Order): Promise&lt;void&gt;;
}
export interface PlaceOrderOutput {            // implemented by the presenter
  present(response: PlaceOrderResponse): void;
}
export type PlaceOrderRequest = {
  customerId: string;
  lines: { sku: string; quantity: number }[];
};
export type PlaceOrderResponse = { orderId: string; itemCount: number };

export class PlaceOrder {
  constructor(private readonly orders: OrderRepository) {}

  async execute(request: PlaceOrderRequest, output: PlaceOrderOutput): Promise&lt;void&gt; {
    const order = Order.place(await this.orders.nextId(), request.customerId, request.lines);
    await this.orders.save(order);
    output.present({ orderId: order.id, itemCount: order.itemCount() });
  }
}
</code></pre>
<p>It imports only the entity. <code>Order.place()</code> throws when an order has no lines or a quantity below one, and the entity file imports nothing. The adapter imports inward, plus the driver:</p>
<pre><code class="language-ts">// src/orders/adapters/postgres/postgres-order-repository.ts
import { randomUUID } from 'node:crypto';
import type { Pool } from 'pg';                         // adapters may import the driver
import type { Order } from '../../entities/order';
import type { OrderRepository } from '../../use-cases/place-order';

export class PostgresOrderRepository implements OrderRepository {
  constructor(private readonly pool: Pool) {}

  async nextId(): Promise&lt;string&gt; { return randomUUID(); }

  async save(order: Order): Promise&lt;void&gt; {
    await this.pool.query('INSERT INTO orders (id, customer_id, lines) VALUES ($1, $2, $3)',
      [order.id, order.customerId, JSON.stringify(order.lines)]);
  }
}
</code></pre>
<p>The composition root alone knows every concrete class:</p>
<pre><code class="language-ts">// src/main.ts
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const controller = new OrderController(new PlaceOrder(new PostgresOrderRepository(pool)));

app.post('/orders', async (req, res) =&gt; {
  const view = await controller.post(req.body);        // the presenter's view model
  res.status(view.status).set(view.headers).json(view.body);
});
</code></pre>
<p>A unit test of <code>PlaceOrder</code> needs only an in-memory repository and a presenter that records its input: no server, no database.</p>
<h3>Folder structure</h3>
<pre><code class="language-text">src/
  orders/
    entities/
      order.ts                        Order and its rules
    use-cases/
      place-order.ts                  PlaceOrder, both interfaces, request and response models
    adapters/
      http/
        order-controller.ts
        order-presenter.ts
      postgres/
        postgres-order-repository.ts
  main.ts                             composition root: builds and wires everything
</code></pre>
<p>Group by feature, then by layer. Martin's screaming architecture argument: top-level folders should say what the system does (orders, payments), not which framework it uses. Simon Brown's chapter in the same book separates organization from encapsulation: folders organize code, while access rules or a build check enforce it.</p>
<h2>Crossing boundaries</h2>
<p>Each boundary crossing carries a type that one layer owns:</p>
<table>
<thead>
<tr>
<th>Crossing</th>
<th>What travels</th>
<th>Type owned by</th>
<th>Mechanism</th>
</tr>
</thead>
<tbody><tr>
<td>Framework → controller</td>
<td>HTTP request</td>
<td>Framework</td>
<td>Glue code in <code>main.ts</code></td>
</tr>
<tr>
<td>Controller → use case</td>
<td><code>PlaceOrderRequest</code></td>
<td>Use cases</td>
<td>Direct call</td>
</tr>
<tr>
<td>Use case → presenter</td>
<td><code>PlaceOrderResponse</code></td>
<td>Use cases</td>
<td><code>PlaceOrderOutput</code> interface</td>
</tr>
<tr>
<td>Use case → database</td>
<td><code>Order</code></td>
<td>Entities</td>
<td><code>OrderRepository</code> interface</td>
</tr>
<tr>
<td>Presenter → framework</td>
<td>View model</td>
<td>Adapters</td>
<td>Returned by the controller</td>
</tr>
</tbody></table>
<p>Three habits keep these crossings clean:</p>
<ul>
<li><strong>Plain request and response models.</strong> Martin is blunt: "We don't want to cheat and pass Entities or Database rows." The presenter gets <code>PlaceOrderResponse</code>, never <code>Order</code>, so renaming an entity field leaves the API alone. Repositories are a common exception: many codebases let them accept entities, which still points inward. Stricter teams map to a persistence record inside the adapter.</li>
<li><strong>An interface at each outward call</strong>, owned by the inner layer and named for what the use case needs, not for the technology.</li>
<li><strong>One composition root.</strong> Mark Seemann defines the <a href="https://blog.ploeh.dk/2011/07/28/CompositionRoot/">composition root</a> as "a (preferably) unique location in an application where modules are composed together," close to the entry point. Martin calls <code>main</code> "the ultimate detail." Everything else receives dependencies through constructors.</li>
</ul>
<p>Martin's figure also has a Use Case Input Port interface in front of the interactor. With one controller and one implementation, calling the class directly is a common simplification.</p>
<h2>Clean vs hexagonal vs onion architecture</h2>
<table>
<thead>
<tr>
<th></th>
<th>Hexagonal (ports and adapters)</th>
<th>Onion</th>
<th>Clean</th>
</tr>
</thead>
<tbody><tr>
<td>Defining text</td>
<td>Alistair Cockburn, 2005 article</td>
<td>Jeffrey Palermo, 2008 blog series</td>
<td>Robert C. Martin, 2012 blog post, 2017 book</td>
</tr>
<tr>
<td>Picture</td>
<td>Application in a hexagon, adapters outside</td>
<td>Rings around the domain model</td>
<td>Four concentric circles</td>
</tr>
<tr>
<td>Structure inside</td>
<td>Not prescribed</td>
<td>Domain model, domain services, application services</td>
<td>Entities, use cases</td>
</tr>
<tr>
<td>Repository implementation</td>
<td>Secondary (driven) adapter</td>
<td>Infrastructure, outer ring</td>
<td>Interface adapters</td>
</tr>
<tr>
<td>Core rule</td>
<td>Inside code must not leak outside; talk through ports</td>
<td>All coupling points toward the center</td>
<td>Source code dependencies point inward</td>
</tr>
</tbody></table>
<p>All three put business rules in the middle and make the edges depend on them. They differ in how much structure they prescribe inside: <a href="https://alistair.cockburn.us/hexagonal-architecture/">Cockburn's original article</a> separates only inside from outside, <a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/">Palermo's onion architecture</a> names rings around the domain model, and clean architecture adds presenters and request and response models. The <a href="https://getarchboard.app/blog/hexagonal-architecture-diagram">hexagonal architecture diagram</a> walks through a similar order example in ports-and-adapters terms.</p>
<h2>Common mistakes</h2>
<ul>
<li><strong>Framework types in entities.</strong> ORM decorators or serialization attributes on <code>Order</code> tie the innermost layer to the outermost. Map in the adapter.</li>
<li><strong>A mapper for everything.</strong> Six copies of the same fields for a form that saves one row. Map only where the shapes differ.</li>
<li><strong>Layers without behavior.</strong> Getter-and-setter entities, the <a href="https://martinfowler.com/bliki/AnemicDomainModel.html">anemic domain model</a> Martin Fowler described in 2003, and use cases that only call <code>save()</code>.</li>
<li><strong>Interfaces everywhere.</strong> They belong at boundaries, not on every class.</li>
<li><strong>HTTP in the use case.</strong> Status codes belong in the presenter.</li>
</ul>
<h2>When it is overkill</h2>
<p>Palermo wrote that onion architecture "is not appropriate for small websites," and Martin's chapter on partial boundaries opens with "Full-fledged architectural boundaries are expensive."</p>
<table>
<thead>
<tr>
<th>Situation</th>
<th>A better fit</th>
</tr>
</thead>
<tbody><tr>
<td>CRUD service with few rules</td>
<td>A thin layered app; keep the few rules out of controllers</td>
</tr>
<tr>
<td>Prototype or short-lived tool</td>
<td>No layers</td>
</tr>
<tr>
<td>One volatile dependency, such as a payment provider</td>
<td>One interface and one adapter for it</td>
</tr>
<tr>
<td>Long-lived product with real rules and several entry points</td>
<td>All four layers</td>
</tr>
</tbody></table>
<p>That chapter also describes cheaper partial boundaries; promote one when a second implementation or a test needs it.</p>
<h2>The clean architecture diagram</h2>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/c735g17yr3z3il65v29o.png" alt="Four UML packages in a row: frameworks and drivers, interface adapters, use cases and entities. The web framework calls OrderController, which calls PlaceOrder, which creates Order. OrderPresenter and PostgresOrderRepository implement interfaces in the use case layer." /></p>
<p><em>One use case, PlaceOrder, traced through the four clean architecture layers, outermost on the left. No arrow points outward: the presenter and the Postgres repository implement interfaces that the use case layer owns, so control flows out while dependencies point in.</em></p>
<p>How to read it:</p>
<ul>
<li><strong>Four UML packages, outermost on the left.</strong> Moving right means moving inward.</li>
<li><strong>Solid arrows are calls and imports.</strong> Three cross a boundary toward the entities. The other three stay within one layer: <code>present(response)</code> and <code>save(order)</code> call the two interfaces the use case layer owns.</li>
<li><strong>Dashed arrows with hollow triangles mean implements.</strong> The presenter and the repository point inward at those interfaces while control flows outward.</li>
<li><strong>The dotted line</strong> is SQL through the driver, and it starts in an adapter.</li>
<li><strong>The notes and the Markdown block</strong> say where <code>main.ts</code> lives, what the entity enforces and what each line style means.</li>
</ul>
<h2>Drawing clean architecture diagrams clearly</h2>
<ul>
<li><strong>Draw one use case, not the rings.</strong> Trace a real feature through real class names.</li>
<li><strong>Put each interface in the layer that owns it.</strong> <code>OrderRepository</code> sits next to <code>PlaceOrder</code>, not next to its implementation.</li>
<li><strong>Use two arrow styles:</strong> solid for calls, dashed with a hollow triangle for implements, as in UML realization. The <a href="https://getarchboard.app/blog/uml-class-diagram-example">UML class diagram example</a> covers the notation.</li>
<li><strong>Give inward one direction on the page.</strong> An arrow pointing back is a violation or a runtime call to label.</li>
<li><strong>Label arrows with the method and the model that crosses.</strong></li>
<li><strong>Leave out</strong> DTO fields, framework internals and the DI container.</li>
</ul>
<p>For the system around this code-level view, see the <a href="https://getarchboard.app/blog/c4-model-diagram-example">C4 model diagram example</a> and the <a href="https://getarchboard.app/blog/how-to-draw-software-architecture-diagram">guide to drawing software architecture diagrams</a>.</p>
<h2>Build it in Archboard</h2>
<ol>
<li>Sign in with Google or GitHub and create a diagram.</li>
<li>Add four <strong>Package</strong> nodes from the <strong>UML</strong> pack in a row: Frameworks and drivers, Interface adapters, Use cases and Entities, with blue, green, red and amber accents.</li>
<li>In Frameworks and drivers, add a <strong>Component</strong> from the <strong>UML</strong> pack named Web framework and a <strong>Postgres</strong> node from the <strong>Data</strong> pack named PostgreSQL.</li>
<li>In Interface adapters, add two <strong>Component</strong> nodes, OrderPresenter and OrderController, and a <strong>Class</strong> named PostgresOrderRepository.</li>
<li>In Use cases, add a <strong>Class</strong> named PlaceOrder between two <strong>Interface</strong> nodes, PlaceOrderOutput and OrderRepository.</li>
<li>In Entities, add a <strong>Class</strong> named Order with its fields and methods.</li>
<li>Draw six solid labeled edges for the calls, two dashed edges with triangle arrowheads for implements, and a dotted edge from PostgresOrderRepository to PostgreSQL.</li>
<li>Add a <strong>Markdown</strong> block from the <strong>Core</strong> pack with the rule and the line styles, and <strong>Text</strong> notes from the <strong>Core</strong> pack for each layer.</li>
</ol>
<p>A Mermaid flowchart of your layers becomes a first draft with the <a href="https://getarchboard.app/tools/mermaid-to-editable-diagram">Mermaid to editable diagram tool</a>. Free allows 15 diagram nodes per diagram, so trace one use case per diagram there.</p>
<p>The example uses 14 diagram nodes, within the Free plan.</p>
<h2>FAQ</h2>
<p><strong>What are the four layers of clean architecture?</strong>
Entities (enterprise business rules), use cases (application business rules), interface adapters (controllers, presenters and gateways) and frameworks and drivers (the web framework, the database and other tools). Martin calls the circles schematic: you may need more than four.</p>
<p><strong>What is the dependency rule?</strong>
Source code dependencies point only inward. Code in an inner layer never names anything declared in an outer layer, so use cases know nothing about controllers, SQL or the web framework.</p>
<p><strong>What is the difference between clean architecture and hexagonal architecture?</strong>
Both keep business rules in the middle and make adapters depend on them. Hexagonal architecture separates only the inside from the outside, through ports. Clean architecture also splits the inside into entities and use cases and names presenters and request and response models.</p>
<p><strong>Where does the repository interface go in clean architecture?</strong>
In the use case layer, next to the use case that needs it. The implementation, with the SQL, belongs in the interface adapters layer, and the composition root passes it in at startup.</p>
<p><strong>Is clean architecture overkill for small projects?</strong>
Often. For CRUD services, prototypes and short-lived tools, the extra interfaces and mappings cost more than they return. Add interfaces for the dependencies you expect to change, and grow the layers when real business rules appear.</p>
<hr />
<p><em>This post was originally published on the <a href="https://getarchboard.app/blog/clean-architecture-diagram">Archboard blog</a>.</em></p>
]]></content:encoded></item></channel></rss>