Skip to content

    AI Architect

    Diagramming AI Systems: C4, Sequence, State, ER

    Draw one AI assistant at every level: context, container, component, sequence, deployment, state, data model and trust boundaries, plus a checklist.

    By Published 27 min read

    Share

    This lesson is part of AI Architect (Intermediate): Design the System. Enroll for free, then sign in, to read it in full.

    What you'll learn: which diagram answers which design-review question, using one teaching system drawn at every level (context, container, component, sequence, deployment, state, data model, trust boundary), and a checklist you can apply to any diagram.

    At a glance

    Figure 1. One system, many views, one checklist

    flowchart LR accTitle: One system, many views, one checklist accDescr: A design-review question is answered by one of four kinds of view. Structure views are context, container and component. Runtime views are sequence and state diagrams. The data view is an ER diagram. Where-it-runs views are deployment and trust boundary. All views use the same component names and pass the same checklist before review. Q["Design-review question"] --> S["Structure: context, container, component"] Q --> R["Runtime: sequence, state"] Q --> D["Data: ER diagram"] Q --> W["Where: deployment, trust boundary"] S --> N["Same component names in every view"] R --> N D --> N W --> N N --> C["Checklist before the review"]

    How to read this: pick the branch that matches the question being asked, and note that every branch ends in the same two gates, shared names and the checklist.

    • A diagram answers one question for one audience. Choose the type from the question.
    • Structure views (context, container, component) say what exists. They say nothing about order.
    • Sequence and state diagrams say what happens: decisions, retries, exits. Draw the failure paths, not only the happy path.
    • Mark trust boundaries and name the control at each crossing. Model output and retrieved text count as untrusted.
    • About 15 nodes is the limit for one view. Keep diagrams as text next to the code.

    The real-world problem

    Composite scenario, not a real company. A team presents a customer-facing assistant that answers from policy documents and can open a support ticket, on one slide with eleven boxes, three arrow styles and a legend nobody can find. Reviewers ask four questions it cannot answer:

    • Where does the customer's identity go after the gateway?
    • What happens if the search step returns nothing?
    • Who retries when the ticket service is slow?
    • Which parts run in the same network as the documents?

    The slide mixes structure, runtime order and deployment in one picture. The fix is a small set of diagrams, each answering one question, drawn from the same component names.

    After this page you will be able to

    • Choose the diagram type that answers a given design-review question.
    • Draw C4-style context, container and component views as architecture diagrams, with consistent names.
    • Draw a sequence diagram for a normal request and for two failure paths.
    • Mark trust boundaries and name the control where a data flow crosses one.
    • Apply the diagram checklist and reject a diagram that fails it.

    Read the AI architect mindset first: each diagram question comes from requirements and constraints. Background:

    Terms used on this page: C4 model, trust boundary, sequence diagram, idempotency key and data flow diagram.

    Core concepts

    One system, drawn at every level

    Every diagram here shows the same invented policy Q&A assistant. A customer asks about a policy (a returns or warranty policy, say). The assistant answers only from approved policy documents, cites the passages it used, and can create a support ticket on request. It is not a real product and every number attached to it is illustrative.

    The course uses fixed component names so diagrams on different pages can be read against each other.

    Name What it does in the teaching system
    Client app The web or mobile front end
    API gateway Authenticates, rate-limits, forwards with a verified identity
    Orchestrator Runs the agent loop: builds the prompt, calls the model, decides about tool calls, checks the output
    Model gateway The single path to model providers: keys, provider-side retries, token accounting
    LLM provider An external service that generates text
    Retriever Turns the question into a search and returns the allowed passages
    Vector index Embeddings of policy passages for similarity search
    Document store The approved policy documents and their versions
    Tool server Exposes the ticket-creation tool
    Policy engine Allow or deny for a tool call, for a given user
    Event bus Carries audit and trace events asynchronously
    Worker Consumes events and writes them to storage
    Trace store Keeps traces and audit events
    Eval service Replays saved cases against a new prompt or model version

    How to read this: use the left column's name in every diagram and in the prose; a renamed box looks like a new component.

    The course-wide Approval service is absent: a ticket created on the customer's own behalf is reversible and customer-initiated, so a Policy engine decision is enough here. A refund would add it. The ticketing system and identity provider are external.

    C4 in one page

    The C4 model, created by Simon Brown and documented at c4model.com, describes software at four zoom levels: system context, containers, components and code. The site calls it "an easy to learn, developer friendly approach to software architecture diagramming". You do not need all four levels, "only those that add value"; context and container diagrams are named as sufficient for most teams.

    Level Scope Primary elements What the C4 site says
    System context One software system The system, with people and external systems around it For everybody; recommended for all teams
    Container One software system The containers inside it For technical people; says very little about deployment
    Component One container The components inside it For architects and developers; only if they add value
    Deployment One or more systems in a single environment Deployment nodes and the instances on them One diagram per environment; icons must be in the key

    How to read this: each row zooms in one step, and deployment is a separate lens on the same containers.

    • A container is "an application or a data store" that "needs to be running in order for the overall software system to work". It is not about Docker, so a client library inside the Orchestrator is not a container.
    • A component is "a grouping of related functionality encapsulated behind a well-defined interface."

    Notation rules worth adopting even without C4 tooling:

    • Every diagram has a title that says its type and scope, and a key or legend.
    • Each diagram stands alone and is mostly understood without a narrative.
    • Every element carries a type and a short description.
    • Every line is labelled and runs one way. Lines between containers name a technology or protocol.
    NOTE

    Here the C4-style views use the site's architecture diagram format (a text spec with zones and labelled arrows): they follow the C4 abstractions but are not C4 tool output. Mermaid's own C4 type is, in its documentation's words, "an experimental diagram for now" whose syntax and properties can change in future releases. A text spec is editable in a pull request. The cost: nothing enforces C4 discipline, which is what the checklist below is for.

    The context view

    The context view shows the system in the middle and only the people and external systems around it.

    Figure 2. Context view of the policy Q&A assistant

    Context view of the policy Q&A assistantCustomer to Policy Q&A assistant (asks over HTTPS); Policy owner to Policy Q&A assistant (publishes); Policy Q&A assistant to LLM provider (prompt, passages); Policy Q&A assistant to Ticketing system (create ticket); Policy Q&A assistant to Identity provider (verify session); Ticketing system to Support agent (in queue)EXTERNAL SYSTEMSCustomer: policy questionsCustomerpolicy questionsPolicy owner: policy documentsPolicy ownerpolicy documentsPolicy Q&A assistant: cited answersPolicy Q&Aassistantcited answersLLM provider: externalLLM providerexternalTicketing system: externalTicketingsystemexternalIdentity provider: externalIdentityproviderexternalSupport agent: works ticketsSupport agentworks ticketsasks over HTTPSpublishesprompt, passagescreate ticketverify sessionin queue

    How to read this: person icons are people, the shaded box groups the external systems the team does not run, and each arrow is one direction with a label saying what travels.

    It leaves out databases, queues and the model gateway on purpose. One decision is already exposed: customer question text leaves the system for an LLM provider. A privacy reviewer needs that on the first diagram, not the tenth.

    The container view

    The container view zooms into the system. Draw the containers that fail, scale and get secured differently, including the asynchronous audit path.

    Figure 3. Container view of the policy Q&A assistant

    Container view of the policy Q&A assistantClient app to API gateway (HTTPS); API gateway to Orchestrator (question, identity); Orchestrator to Retriever (search, entitlements); Retriever to Vector index (similarity search); Retriever to Document store (approved passages); Orchestrator to Model gateway (prompt); Model gateway to LLM provider (HTTPS); Orchestrator to Policy engine (may this run?); Orchestrator to Tool server (tool call, key); Tool server to Ticketing system (HTTPS); Orchestrator to Event bus (audit event); Event bus to Worker (consume); Worker to Trace store (write); Eval service to Trace store (read cases)POLICY Q&A ASSISTANT (SYSTEM BOUNDARY)Client appClient appLLM provider: externalLLM providerexternalTicketing system: externalTicketingsystemexternalModel gatewayModel gatewayTool serverTool serverVector indexVector indexAPI gatewayAPI gatewayOrchestratorOrchestratorRetrieverRetrieverDocument storeDocument storePolicy enginePolicy engineEvent busEvent busWorkerWorkerTrace storeTrace storeEval serviceEval serviceHTTPSquestion, identitysearch, entitlementssimilarity searchapproved passagespromptHTTPSmay this run?tool call, keyHTTPSaudit eventconsumewriteread cases

    How to read this: solid arrows are synchronous calls that the customer waits for, dashed arrows are asynchronous, database icons are stores, and the large box is the system boundary.

    • The Orchestrator is the only container that talks to the Retriever, Model gateway, Policy engine and Tool server, so the next view zooms into it.
    • The audit path is asynchronous. What happens when the Event bus is down belongs in a failure sequence, not here.
    • Left out to stay near the node limit: the identity provider and the ingestion path that fills the Document store and Vector index. A real view would show both.

    The component view

    A component view decomposes one container, and only when it adds value. For the Orchestrator it does: the agent loop holds most AI-specific decisions.

    Figure 4. Component view of the Orchestrator

    Component view of the OrchestratorAPI gateway to Input checks (question, identity); Input checks to Context builder (accepted request); Context builder to Retriever (search); Context builder to Agent loop (prompt context); Agent loop to Model gateway (prompt); Agent loop to Tool dispatcher (tool request); Tool dispatcher to Policy engine (allow or deny?); Tool dispatcher to Tool server (approved call); Tool dispatcher to Agent loop (result or refusal); Agent loop to Output checks (draft answer); Output checks to API gateway (answer); Input checks to Audit emitter (event); Tool dispatcher to Audit emitter (event); Output checks to Audit emitter (event); Audit emitter to Event bus (async)ORCHESTRATOR (CONTAINER)API gatewayAPI gatewayRetrieverRetrieverModel gatewayModel gatewayInput checksInput checksContext builderContextbuilderAgent loopAgent loopOutput checksOutput checksTool dispatcherTooldispatcherAudit emitterAudit emitterPolicy enginePolicy engineTool serverTool serverEvent busEvent busquestion, identityaccepted requestsearchprompt contextprompttool requestallow or deny?approved callresult or refusaldraft answeranswereventeventeventasync

    How to read this: the large box is one container, the boxes inside it are components with one responsibility each, dashed arrows are asynchronous events, and everything outside the box is another container from Figure 3.

    Component One responsibility The rule that lives here
    Input checks Reject oversize or malformed requests Before any model spend
    Context builder Choose which passages and conversation parts go in the prompt What the model sees
    Agent loop Own the step budget How many tool rounds
    Tool dispatcher The only code that may call the Tool server The Policy engine check, in one place
    Output checks Verify, for example, that every citation was retrieved What reaches the customer
    Audit emitter Written once, used by the others No path forgets to log

    How to read this: each row is a box in Figure 4, and the last column is why that box exists.

    Sequence diagrams for runtime behaviour

    Structure diagrams do not say what happens in what order. A sequence diagram shows participants as vertical lifelines and messages as arrows read top to bottom. The C4 site's dynamic diagram shows "how elements in the static model collaborate at runtime to implement a user story, use case, feature", in either collaboration or sequence style.

    You want Mermaid syntax
    A short name for a lifeline participant X as Name
    Request and reply ->> and -->>
    An asynchronous message -)
    A decision at a point in time Note over A,B: text
    Alternatives, optional steps, repeats, parallel work alt / else, opt, loop, par
    Numbered steps autonumber

    How to read this: the left column is the need, the right column is the syntax this page's figures use.

    Mermaid's documentation warns that the word "end" can break a diagram, that a semicolon acts as a line break and that # needs an entity code, so avoid them in message text. Draw one sequence per scenario, with at most about eight participants, and put each decision in a note where the system makes it.

    Figure 5. Normal question, answered from the policy documents

    sequenceDiagram accTitle: Normal question sequence accDescr: The Client app sends a question through the API gateway to the Orchestrator. The Orchestrator searches with the Retriever, asks the LLM provider through the Model gateway, checks the answer, publishes an audit event and returns the answer. autonumber participant C as Client app participant G as API gateway participant O as Orchestrator participant R as Retriever participant M as Model gateway participant L as LLM provider participant E as Event bus C->>G: question over HTTPS with session token G->>O: question plus verified user identity O->>R: search(question, user entitlements) R-->>O: top passages with document ids and versions O->>M: prompt with question and passages M->>L: model request L-->>M: draft answer with citations M-->>O: draft answer plus token counts Note over O: Output check - every cited id must be among the retrieved passages O-)E: audit event outcome=answered O-->>G: answer with citations G-->>C: answer with citations

    How to read this: time runs downward, solid arrows are requests, dotted arrows are replies, the open-headed arrow is asynchronous, and the note marks a decision the Orchestrator makes.

    The happy path is the least informative diagram you can draw. The next two show what the design does when things go wrong.

    Figure 6. Failure path: the retrieval step returns nothing or times out

    sequenceDiagram accTitle: Retrieval failure sequence accDescr: The Orchestrator searches with the Retriever. If the Retriever replies in time with no relevant passages, or does not reply within the retrieval timeout, the Orchestrator does not call the Model gateway. It records the outcome, tells the customer it found nothing, and offers to create a ticket. autonumber participant C as Client app participant G as API gateway participant O as Orchestrator participant R as Retriever participant E as Event bus C->>G: question G->>O: question plus verified user identity O->>R: search(question, user entitlements) with 1 s timeout alt Retriever replies in time R-->>O: 0 passages above the relevance threshold Note over O: Decision - no evidence, so no model call O-)E: audit event outcome=no_evidence else No reply within the timeout Note over O: Decision - retrieval unavailable, so no model call O-)E: audit event outcome=retrieval_unavailable end O-->>G: no answer found plus an offer to create a ticket G-->>C: no answer found plus an offer to create a ticket

    How to read this: the alt block shows two alternatives that end in the same customer message, and the notes mark the decisions.

    With no evidence, the Orchestrator does not call the model at all. A model asked a policy question with no passages can still produce a fluent answer from its training data, which the system promised not to do. Retrying the Retriever once is a design choice; if you make it, the diagram must show it and the timeout budget must pay for it.

    Check yourself: in Figure 6, how many calls reach the Model gateway when the Retriever returns zero passages?

    None. The note "no evidence, so no model call" is a decision, and the Orchestrator goes straight to the audit event and the customer message.

    Step through Figure 5 and Figure 6 side by side: pick a track and read what each step decides.

    Normal question versus empty retrieval (policy Q&A assistant, illustrative) (interactive when JavaScript is on)

    Normal question

    1. Authenticate at the gateway. The gateway passes a verified identity on, so the Orchestrator never trusts an identity claim from the Client app.
    2. Search with entitlements. The user's entitlements travel with the search, so the Retriever returns only documents this customer may see.
    3. Passages return with ids and versions. Those ids and versions are what citations can refer to.
    4. Call the model. Only the Model gateway talks to the LLM provider.
    5. Output check. An answer citing a passage the Retriever never returned is rejected.
    6. Audit and reply. The audit event is asynchronous, off the critical path. The answer returns with citations.

    Retrieval returns nothing

    1. Authenticate and search. Same start, with a 1 s timeout on the search.
    2. No usable result. The Retriever returns 0 passages above the threshold, or does not reply in time.
    3. Decide: no model call. With no evidence the model could answer from training data, so the Orchestrator skips it.
    4. Record and reply. Audit outcome no_evidence or retrieval_unavailable. The customer is told nothing was found and offered a ticket.

    Figure 7. Failure path: the ticket tool times out

    sequenceDiagram accTitle: Ticket tool timeout sequence accDescr: The Orchestrator asks the Policy engine whether the ticket call is allowed, then calls the Tool server with an idempotency key. The first call times out. The Orchestrator retries once with the same key. If the second call succeeds the ticket is confirmed. If it also times out, the Orchestrator makes no third attempt, reports honestly that the ticket was not confirmed, and records the failure. autonumber participant O as Orchestrator participant P as Policy engine participant T as Tool server participant K as Ticketing system participant E as Event bus O->>P: may this customer create a ticket of this type? P-->>O: allow O->>T: create_ticket(summary, key k1) with 3 s timeout T->>K: create ticket with key k1 Note over O,T: No reply within 3 s - the first attempt is abandoned Note over O: For this tool call the Orchestrator is the only layer that retries O->>T: create_ticket(summary, key k1) after 0.5 s backoff T->>K: create ticket with key k1 alt Second attempt replies in time T-->>O: ticket id for key k1 O-)E: audit event outcome=ticket_created else Second attempt also times out Note over O: No third attempt - report honestly O-)E: audit event outcome=ticket_unconfirmed end

    How to read this: the two notes explain the timeout and who owns retries, and the alt block shows the success and failure endings of the single retry.

    This diagram carries three decisions:

    Decision What the figure shows Why
    Policy check first The Policy engine is asked before the call, and a deny would end the sequence at step 2 A check after the call cannot undo the ticket
    Same idempotency key on the retry Both attempts carry key k1 The first attempt may have reached the ticketing system even though its reply was lost
    Exactly one retrying layer A note says the Orchestrator is the only layer that retries Retries at several levels multiply

    How to read this: each row is one decision visible in Figure 7, with the reason it is there.

    An idempotency key is a value the caller supplies so that repeating the same request has the effect of doing it once. Somewhere on the path (the Tool server, or a ticketing system that honours keys) a store of keys must return the existing ticket id on a repeat.

    On retry multiplication, the Google SRE book warns against "amplifying retries by issuing retries at multiple levels": three layers each making 4 attempts can produce 4^3 = 64 attempts on the database for one user action. The billing-dispute case file draws multi-layer retries in detail.

    Check yourself: the ticket call times out twice. How many create_ticket attempts reach the Tool server, and which key do they carry?

    Two, both with key k1. There is no third attempt, the Orchestrator reports honestly that the ticket was not confirmed, and the audit event is ticket_unconfirmed.

    The deployment view

    The deployment view answers where each container runs and who controls the network between them. Draw one per environment.

    Figure 8. Deployment view of the production environment (instance counts are illustrative)

    Production deployment viewClient app to API gateway (HTTPS); API gateway to Orchestrator (question, identity); Orchestrator to Retriever (search); Orchestrator to Model gateway (prompt); Orchestrator to Policy engine (may this run?); Orchestrator to Tool server (tool call); Retriever to Vector index (similarity search); Retriever to Document store (fetch passages); Orchestrator to Event bus (audit event); Event bus to Worker (consume events); Worker to Trace store (write); Model gateway to LLM provider (HTTPS); Tool server to Ticketing system (HTTPS)PUBLIC ZONEPRIVATE APPLICATION ZONEDATA ZONEClient app: customer deviceClient appcustomer deviceAPI gateway: 2 instancesAPI gateway2 instancesPolicy engine: 2 instancesPolicy engine2 instancesOrchestrator: 3 instancesOrchestrator3 instancesModel gateway: 2 instancesModel gateway2 instancesWorker: 2 instancesWorker2 instancesRetriever: 2 instancesRetriever2 instancesTool server: 2 instancesTool server2 instancesLLM provider: third partyLLM providerthird partyTicketing system: third partyTicketingsystemthird partyEvent busEvent busVector indexVector indexDocument storeDocument storeTrace storeTrace storeHTTPSquestion, identitysearchpromptmay this run?tool callsimilarity searchfetch passagesaudit eventconsume eventswriteHTTPSHTTPS

    How to read this: shaded boxes are deployment zones, a stacked box says how many instances run, and arrows follow the same directions as Figure 3.

    The data zone has no inbound path from the public zone. The Eval service is left out to keep the figure small. Staging needs its own diagram: counts, network rules and which third-party service is real will differ.

    Check yourself: which containers in Figure 8 have a path out to third parties, and what does that mean for egress rules?

    The Model gateway (to the LLM provider) and the Tool server (to the ticketing system). Egress rules attach to those two.

    State diagrams for agents and workflows

    Draw a state diagram when a component has modes and the rules for moving between them matter. An agent loop is the standard case. Mermaid's stateDiagram-v2 has [*] for start and end, labelled transitions and a <<choice>> node for a branch.

    Figure 9. State of one request in the Orchestrator's agent loop

    stateDiagram-v2 accTitle: Agent loop states for one request accDescr: A request is received, then retrieves evidence, then reasons with the model and reaches a decision. The decision is either a final answer, a tool request that goes through a policy check, or a stop because the step budget is used up. Tool calls return to reasoning. Every path ends in a terminal outcome. state Decide <> [*] --> Received Received --> Retrieving: identity verified Received --> Rejected: input check fails Retrieving --> NoEvidence: nothing found or timeout Retrieving --> Reasoning: passages found Reasoning --> Decide: model reply received Reasoning --> Failed: model call fails after retry Decide --> Answering: final text Decide --> PolicyCheck: tool request and steps left Decide --> StepLimit: tool request and no steps left PolicyCheck --> CallingTool: allow PolicyCheck --> Refused: deny CallingTool --> Reasoning: tool result returned CallingTool --> ToolFailed: tool call fails after retry Answering --> [*] Rejected --> [*] NoEvidence --> [*] Failed --> [*] StepLimit --> [*] Refused --> [*] ToolFailed --> [*]

    How to read this: each rounded box is a state, each arrow is a transition with the condition that triggers it, the diamond is a choice made in one instant, and the black dot and ringed dot are start and end.

    The value of a state diagram is exhaustiveness. Count the exits: seven terminal outcomes (answered, rejected, no evidence, model failure, step limit, refused, tool failure), each emitting exactly one audit event. A situation a reviewer can name with no outgoing arrow is a gap. The diagram says which moves are legal, not what the messages are.

    Check yourself: in Figure 9, which transition is the only cycle, and which node is the only place that tests the step budget?

    CallingTool back to Reasoning is the only cycle, and the Decide choice node is the only budget test. So an agent that keeps asking for tools ends in StepLimit instead of running up cost indefinitely.

    Data-model views

    A data-model view is an entity-relationship (ER) diagram. Use it for data that must outlive a request: audit records and the evaluation dataset that a regulator, an on-call engineer or the Eval service will query later. Mermaid writes a relationship as A ||--o{ B : label, with two characters per side, the outer one the maximum and the inner one the minimum:

    • || exactly one, o| zero or one
    • }o or o{ zero or more, }| or |{ one or more
    • a solid line is an identifying relationship (the child cannot exist without the parent), a dashed line is non-identifying
    • attributes are written type name and may be marked PK, FK or UK

    Figure 10. Data model of the audit log and the eval dataset

    erDiagram accTitle: Audit log and eval dataset data model accDescr: A conversation has many requests. Each request has retrieved passages, tool calls and audit events. An eval case may be promoted from a real request. An eval run produces one result per eval case. CONVERSATION ||--o{ REQUEST : has REQUEST ||--o{ RETRIEVED_PASSAGE : "used as evidence" REQUEST ||--o{ TOOL_CALL : triggers REQUEST ||--o{ AUDIT_EVENT : emits REQUEST |o--o{ EVAL_CASE : "promoted into" EVAL_RUN ||--o{ EVAL_RESULT : produces EVAL_CASE ||--o{ EVAL_RESULT : "scored in" CONVERSATION { string conversation_id PK string user_ref datetime started_at } REQUEST { string request_id PK string conversation_id FK datetime received_at string outcome string prompt_version string model_id } RETRIEVED_PASSAGE { string request_id FK string doc_id string doc_version int rank float score } TOOL_CALL { string tool_call_id PK string request_id FK string tool_name string idempotency_key string status int attempts } AUDIT_EVENT { string event_id PK string request_id FK string event_type datetime recorded_at } EVAL_CASE { string case_id PK string source_request_id FK string question string expected_outcome } EVAL_RUN { string run_id PK datetime started_at string prompt_version string model_id } EVAL_RESULT { string run_id FK string case_id FK string outcome boolean grounded }

    How to read this: each box is a table, each line is a relationship whose end marks say one or many, and PK and FK mark keys.

    Decision Why
    The request carries prompt_version and model_id An answer ties to the exact configuration that produced it, so a regression is traceable
    Passages are stored as doc_id plus doc_version, not copied text The log records the evidence without duplicating policy text, and "which answers cited the old returns policy?" becomes a query
    Audit events hold identifiers and outcomes, not conversation text This system keeps personal data out of the log; a different retention rule would change it
    An eval case may point back to a request (source_request_id is nullable) Production traffic feeds the Eval service, and hand-written cases still fit

    How to read this: each row is one design choice visible in Figure 10, with the reason for it.

    The last row hides a tension: promoting a request into an eval case copies its question into the dataset, although the request record keeps no question text. That step needs its own redaction and consent rule.

    Trust boundaries in diagrams

    A trust boundary is drawn where control changes hands. Microsoft's Threat Modeling Tool documentation says trust boundaries show "where different entities are in control". They are drawn on a data flow diagram (DFD), which the OWASP Threat Modeling Cheat Sheet says will "visually model a system, its data flows, and interactions with external entities".

    • OWASP says threat modelling is "ideally performed early in the SDLC, such as during the design phase", and that a model "should be maintained, updated and refined alongside the system".
    • Both sources use STRIDE to ask what can go wrong at each crossing: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege.

    For an AI system there is one extra rule: model output and retrieved text are data from the wrong side of a boundary, even though they arrive from components you run. The prompt contains text you did not write, and that text can influence the reply. So the Orchestrator treats the reply as a request to be checked, not a command, which is why the Policy engine sits between the agent loop and the Tool server.

    Figure 11. Trust-boundary view of the policy Q&A assistant

    Trust-boundary viewClient app to API gateway (B1: TLS, session token); API gateway to Orchestrator (B2: identity, limits); Orchestrator to Policy engine (may this run?); Orchestrator to Retriever (search); Orchestrator to Model gateway (prompt); Orchestrator to Tool server (tool call); Retriever to Vector index (B3: entitlement filter); Retriever to Document store (B3: approved docs only); Model gateway to LLM provider (B4: prompt text only); LLM provider to Model gateway (B4: reply untrusted); Tool server to Ticketing system (B5: scoped credential)1: CUSTOMER DEVICE2: EDGE3: APPLICATION4: DATA5: THIRD PARTIESClient app: untrustedClient appuntrustedAPI gatewayAPI gatewayOrchestratorOrchestratorRetrieverRetrieverModel gatewayModel gatewayTool serverTool serverPolicy enginePolicy engineVector indexVector indexDocument storeDocument storeLLM providerLLM providerTicketing systemTicketingsystemB1: TLS, session tokenB2: identity, limitsmay this run?searchprompttool callB3: entitlement filterB3: approved docs onlyB4: prompt text onlyB4: reply untrustedB5: scoped credential

    How to read this: arrows with a plain label stay inside a zone, arrows whose label starts B1 to B5 cross a trust boundary and name the control at that crossing.

    Use this view as a review checklist: each B1 to B5 arrow is a place to ask what an attacker or a mistake could do.

    Crossing What to ask Control on the figure
    B1 Client app to API gateway Spoofing and tampering from an untrusted device TLS and session token
    B2 API gateway to Orchestrator Is identity a verified claim or just a header? Verified identity, rate limit, size limit
    B3 Retriever to the data stores Could one customer's documents rank for another? Entitlement-filtered query, approved documents only
    B4 Model gateway and LLM provider, both ways Outbound text leaves your control; the reply returns as untrusted data Prompt text only, no secrets or identity; reply untrusted
    B5 Tool server to ticketing system Does the credential allow more than it needs? Service credential, ticket scope only

    How to read this: each row is a B1 to B5 arrow from Figure 11, with the reviewer's question and the control the figure names.

    The first case file below is a review in which a crossing, between the Orchestrator and a shared Tool server, was missing from the diagram, and with it the control.

    Check yourself: which crossing in Figure 11 is two-way, and why does that matter?

    B4. Outbound prompt text leaves your control, and the reply returns into it as untrusted data, so the crossing needs a control in each direction.

    Decision trees

    A decision tree is a flowchart whose nodes are questions and whose leaves are outcomes. Keep questions answerable with yes or no, and make every leaf an action.

    Figure 12. Which diagram answers my question?

    flowchart TD accTitle: Choosing a diagram type accDescr: A chain of yes or no questions leads from the thing you need to explain to the diagram type that explains it. If none apply, write a short paragraph instead. Start(["What do I need to explain?"]) Q1{"Is the question who uses it and what it depends on?"} Q2{"Is it about the parts and how they connect?"} Q3{"Is it about the order in which things happen?"} Q4{"Is it about the modes it can be in and what moves it between them?"} Q5{"Is it about what data is stored and how it is related?"} Q6{"Is it about where it runs or where trust changes?"} A1["Context view"] A2["Container view, then a component view for one container"] A3["Sequence diagram, one per scenario"] A4["State diagram"] A5["ER diagram"] A6["Deployment view or trust-boundary view"] A7["Write a short paragraph"] Start --> Q1 Q1 -->|"yes"| A1 Q1 -->|"no"| Q2 Q2 -->|"yes"| A2 Q2 -->|"no"| Q3 Q3 -->|"yes"| A3 Q3 -->|"no"| Q4 Q4 -->|"yes"| A4 Q4 -->|"no"| Q5 Q5 -->|"yes"| A5 Q5 -->|"no"| Q6 Q6 -->|"yes"| A6 Q6 -->|"no"| A7

    How to read this: start at the top, follow yes or no at each diamond, and stop at the first rectangle.

    The questions run from broad to narrow, so a team that skips the context view is pointed to it first. The tree picks the next diagram, not the only one, and it ends in prose because sometimes a sentence is the better picture.

    Try the tree on four review questions.

    Which diagram answers this review question? (interactive when JavaScript is on)

    Who retries when the ticket service is slow, and how many times?

    • Context view
    • Sequence diagram of the timeout path
    • ER diagram
    Answer

    Sequence diagram of the timeout path. Order, timeouts and retry ownership are runtime behaviour, which a sequence diagram with the failure path drawn shows.

    Can the agent keep asking for tools forever?

    • ER diagram
    • Context view
    • State diagram
    Answer

    State diagram. The state diagram shows every legal move and exit; its choice node tests the step budget.

    Which arrows carry a named control, such as a ticket-scoped credential?

    • Container view
    • Trust-boundary view
    • State diagram
    Answer

    Trust-boundary view. The trust-boundary view marks each crossing and labels the control applied there.

    How do you find answers that cited an old policy version?

    • ER diagram
    • Sequence diagram
    • Deployment view
    Answer

    ER diagram. The data-model view shows requests linked to retrieved passages by doc_id and doc_version.

    The diagram checklist

    Apply this list to every diagram in a review. Several items come from c4model.com's notation guidance (title, key, labelled lines, stand-alone readability, black-and-white printing and colour blindness). The node limit and the failure-path rule are house rules for this course.

    Check Pass condition Why
    One-sentence caption A figure title and one sentence say what question it answers A diagram without a question cannot be judged
    Legend Shapes, line styles and zone markers are explained beside it The notation must not depend on the author being present
    No colour-only meaning Shape, line style or text carries whatever colour shows Colour fails in print and for colour-blind readers
    About 15 nodes at most Over that, split into an overview and zoom-ins Reviewers stop reading dense pictures
    Consistent names Same name in every diagram and in the text A renamed box looks like a new component
    Labelled arrows One direction and a label for what travels An unlabelled arrow hides the contract
    Failure paths shown At least one diagram shows timeout, empty result or denial Happy paths hide the real design
    Trust boundaries marked Crossings are visible and name their control Data leaks and escalations happen here
    Source in the repository Text next to the code, reviewed with it Diagrams that live elsewhere drift

    How to read this: a diagram passes review only if every row's pass condition is true.

    Case files

    Two composite case files show these diagrams doing real review work. Both are illustrative scenarios, not real companies.

    • Helpdesk assistant design review: a missing trust boundary. Problem: a B2B support assistant let the model choose the tenant id passed to a shared tool server that could read every tenant. Pattern: draw trust boundaries on the container view and ask what controls each crossing.
    • Billing dispute assistant: retries in three layers. Problem: three layers each retried a failing call, which would multiply load in an outage. Pattern: a runtime sequence with the retry loops visible shows who owns retries and exposes amplification the container view hides.

    Decision framework

    Figure 13. When to add which view

    flowchart TD accTitle: When to add which view accDescr: A chain of six checks. Each yes adds a view or practice and then moves on to the next check. Non-engineers in the audience mean start with the context view. Three or more participants or any asynchronous step mean a sequence diagram. A loop or more than one ending means a state diagram. Crossing to a party you do not control, or model output that can trigger an action, means a trust boundary. More than about 15 nodes means split the view. Fast-changing systems mean diagrams as text in the repository. S(["A design needs diagrams"]) --> C1{"Non-engineers in the audience?"} C1 -->|"yes"| A1["Start with the context view"] C1 -->|"no"| C2 A1 --> C2{"3 or more participants, or an async step?"} C2 -->|"yes"| A2["Sequence diagram"] C2 -->|"no"| C3 A2 --> C3{"Can loop or end more than one way?"} C3 -->|"yes"| A3["State diagram, every state has an exit"] C3 -->|"no"| C4 A3 --> C4{"Crosses to a party you do not control, or model output or retrieved text can trigger an action?"} C4 -->|"yes"| A4["Mark trust boundary and name its control"] C4 -->|"no"| C5 A4 --> C5{"Over about 15 nodes?"} C5 -->|"yes"| A5["Split into overview and zoom-in"] C5 -->|"no"| C6 A5 --> C6{"System changes faster than slides?"} C6 -->|"yes"| A6["Keep diagrams as text, review in pull requests"]

    How to read this: unlike Figure 12, the checks are not exclusive; walk down the whole chain and add every view whose question is yes.

    If Then Because Revisit when
    Anyone in the audience is not an engineer Start with the context view It is the only level everybody can read External systems change
    3 or more participants, or any async step Draw a sequence diagram Ordering and retry ownership are invisible in prose A participant is added
    A component can loop or end in more than one way Add a state diagram, check every state has an exit Unbounded loops are a cost and safety failure The step budget or an outcome changes
    Data crosses to a party you do not control, or model output or retrieved text can trigger an action Mark a trust boundary and name its control The crossing is where review time is best spent A tool, data source or provider is added
    A diagram passes about 15 nodes Split into overview and zoom-in A reviewer who cannot hold the picture cannot challenge it Split views start to repeat boxes
    The system changes faster than the slides Keep diagrams as text, review in pull requests A diagram not checked with the code is wrong within weeks Tooling cannot render the format

    Comparison of the main options

    Diagram Question it answers Audience Strength Weakness
    Context view Who uses it and what does it depend on? Everyone Fast agreement on scope Hides everything inside
    Container view What are the parts and how do they talk? Engineers and ops Shows what fails and scales separately Silent on order and deployment
    Component view How is one container organised? Developers Shows where a rule lives Goes stale; draw it only where it adds value
    Sequence diagram In what order, and who owns the retry? Engineers Exposes timeouts, retries, decisions One scenario per diagram
    Deployment view Where does it run, on what network path? Platform and security Makes egress, zones and counts explicit One per environment
    State diagram What modes and legal transitions exist? Engineers Proves every state has an exit Says nothing about messages
    ER diagram What is stored and how is it related? Engineers, auditors Makes audit and eval data explicit Says nothing about behaviour
    Trust-boundary view Where does trust change, and what controls it? Security and architects Turns a review into a walk along crossings Needs honest zones
    Decision tree Which choice applies in which condition? Anyone following a rule Removes ambiguity Unreadable beyond a dozen questions

    Failure scenarios to design for

    These are failures of the diagramming practice, each with the behaviour a team should define in advance.

    Failure What the system does Why
    The diagram and the system drift apart Diagrams are text in the same repository, changed in the same pull request as the code; the review asks whether the pull request touches a diagram A diagram not checked with the code goes stale
    The diagram outgrows a reviewer At about 15 nodes it is split into an overview plus zoom-ins, and the overview names which zoom-in covers which box Reviewers stop reading dense pictures
    Only the happy path is drawn Each user-facing sequence has companions for empty-result, timeout and denial, and no state lacks an exit Happy paths hide the real design
    Names change between diagrams A shared name list is part of the design document; a rename changes everywhere in one commit A renamed box looks like a new component
    Colour carries the meaning Legends describe shape and line style; the diagram is reviewed once in greyscale Colour fails in print and for colour-blind readers
    A trust boundary exists in the system but not the picture The review walks every outbound arrow from the application zone and asks which boundary it crosses and who holds the credential; no answer is a finding Crossings are where data leaks and escalations happen

    Worked example

    Use Figures 5 and 7 to set the timeout budget for the longest path: a customer question that ends in a ticket. A budget is the maximum time each step may take, so the sum fits inside the deadline the customer experiences.

    Assumptions:

    • The figures are illustrative, not measurements. The customer-facing deadline is 20 s.
    • Gateway and identity 0.1 s; retrieval one attempt with a 1.0 s timeout; Policy engine check 0.1 s.
    • Each model call has a 6 s budget in total (including any Model gateway retry). One call precedes the tool request, one follows the tool result.
    • The ticket call has a 3 s timeout, one retry after 0.5 s backoff, and no other layer retries.
    Step Budget (s) Basis
    Gateway and identity 0.1 Assumed
    Retrieval 1.0 One attempt, 1.0 s timeout
    Model call 1 (tool request) 6.0 Total budget including provider-side retries
    Policy check 0.1 Assumed
    Ticket call with one retry 6.5 3.0 + 0.5 + 3.0
    Model call 2 (final text) 6.0 Total budget including provider-side retries
    Total 19.7 0.1 + 1.0 + 6.0 + 0.1 + 6.5 + 6.0

    The deadline is 20 s, so the margin is 0.3 s. The margin is the result: the design has no room for a second retry anywhere, and a slower model timeout must be paid for by removing something else. Raise a model stage by 0.4 s and the budget goes over by 0.1 s.

    Worst-case budget for a question that ends in a ticket (seconds, illustrative) (interactive when JavaScript is on)
    Gateway and identity0.1 s
    Retrieval1 s
    Model call 16 s
    Policy check0.1 s
    Ticket call with retry6.5 s
    Model call 26 s
    Total19.7 s of 20 s
    Slack0.3 s

    Compare retries in several layers. If the gateway, the Orchestrator and the Tool server each made up to 3 attempts, one customer action could reach 3 x 3 x 3 = 27 attempts at the ticketing system. That is why Figure 7 notes that the Orchestrator is the only layer that retries.

    The AWS Builders' Library makes the same point for a five-deep stack with three retries at each layer: "If each layer retries independently, the load on the database will increase 243x". The article gives the figure without the arithmetic, and its best practice is to retry at a single point in the stack.

    A diagram lint for pull requests

    The repository's checker parses every Mermaid block. This short script enforces what parsing cannot: each block needs accTitle and accDescr, and a flowchart should stay near 15 nodes. The node count is a heuristic (ids declared with a shape, after quoted labels are blanked out), so a warning is a prompt to look, not proof.

    import re, sys
    
    MAX_NODES = 15
    FENCE = "`" * 3
    BLOCK = re.compile("^" + FENCE + r"mermaid\s*\n(.*?)^" + FENCE, re.S | re.M)
    NODE = re.compile(r"(?<![\w-])([A-Za-z]\w*)\s*(?:\(\[|\[\(|\[\[|\[|\(|\{)")
    
    def lint(path):
        text = open(path, encoding="utf-8").read()
        problems = []
        for n, m in enumerate(BLOCK.finditer(text), 1):
            body = m.group(1)
            first = next((l.strip() for l in body.splitlines() if l.strip()), "")
            if "accTitle:" not in body or "accDescr:" not in body:
                problems.append(f"diagram {n}: missing accTitle or accDescr")
            if first.startswith(("flowchart", "graph")):
                ids = set()
                for line in body.splitlines():
                    if line.strip().startswith(("accTitle", "accDescr", "subgraph")):
                        continue
                    line = re.sub(r'"[^"]*"|\|[^|]*\|', '""', line)
                    ids.update(NODE.findall(line))
                if len(ids) > MAX_NODES:
                    problems.append(f"diagram {n}: {len(ids)} nodes, over {MAX_NODES}")
        return problems
    
    if __name__ == "__main__":
        bad = {p: lint(p) for p in sys.argv[1:]}
        for p, errs in bad.items():
            for e in errs:
                print(f"{p}: {e}")
        sys.exit(1 if any(bad.values()) else 0)

    Run it as python lint_diagrams.py content/learning/*.mdx in CI. It skips subgraph lines so zone titles are not counted as nodes.

    Common mistakes

    • Mixing levels in one picture. Give each diagram one scope; c4model.com defines a scope for every diagram type.
    • Calling a library a container. A container must be running for the system to work; a library is a component or code element.
    • Unlabelled arrows. Say what travels and, between containers, which protocol.
    • A sequence diagram that is only the happy path. Add an alt block for each empty-result, timeout and denial.
    • Treating model output as trusted. Route the LLM reply through a Policy engine check before it reaches the Tool server.
    • Colour as the only legend. Use a shape, a line style or a word.

    Try it

    Time: 30 to 40 minutes. Pick one AI feature you know (or invent a small one, such as a meeting-summary assistant that posts to a chat tool).

    1. Write its one-sentence caption: who asks what, and what the system does.
    2. Draw its context view (at most seven boxes) and container view (at most 15 nodes) as architecture diagrams.
    3. Draw one sequence diagram for the normal path and one for a failure path (empty retrieval or tool timeout), with a note at each decision.
    4. Mark every trust boundary on the container view with arrows labelled B1 to B5 and the control.
    5. Walk the checklist, then run node scripts/check-diagrams.mjs <your file>, which checks the architecture specs and the Mermaid blocks.

    Done when each diagram has a figure title, an accessible title and description, consistent component names, and you can point to the failure path and the trust boundary for the feature.

    Key takeaways

    • A diagram answers one question for one audience. Pick the type from the question, not from habit.
    • C4 gives four zoom levels and a notation discipline; here its views are architecture diagrams with zones.
    • Sequence diagrams carry the runtime decisions: empty retrieval, retry ownership, the idempotency key.
    • A state diagram proves a loop ends and every outcome has an exit and an audit event.
    • A data-model view links production requests to the audit log and the Eval service.
    • Mark trust boundaries; treat model output and retrieved text as untrusted data.
    • Keep diagrams as text in the repository. About 15 nodes is the limit for one view.

    Self-check

    1. A reviewer asks "what happens if search returns nothing?" Which diagram answers it, and what must it show?

    A sequence diagram for the failure path: the Retriever reply or timeout, the decision not to call the model, the audit outcome and what the customer is told. A container view has no order and no decisions.

    2. In the C4 model, is a Python library used inside the Orchestrator a container? Why or why not?

    No. A container is an application or data store that has to be running for the system to work (c4model.com adds that it is not about Docker). A library is part of a component or code element.

    3. The ticket call times out and the Orchestrator retries. Why does the retry reuse the same idempotency key?

    The first attempt may have reached the ticketing system even though its reply was lost. With the same key the Tool server can return the existing ticket id instead of creating a duplicate.

    4. Three layers each make 3 attempts at a failing call. How many attempts reach the failing service for one user action, and what is the remedy?

    3 x 3 x 3 = 27 attempts. Retry at a single point in the stack, with a retry budget, and return an overload signal that tells other layers not to retry.

    5. Which arrows on a trust-boundary view deserve the most review time in an AI system, and why?

    Arrows where data crosses to a party you do not control (outbound prompts, third-party tools) and where untrusted text can trigger an action (model output heading to a tool). Each needs a named control.

    Further reading

    Last verified: 2026-10-21

    Next

    This is the last page of Part A. Part B starts with page 4: Models, Routing and Inference for AI Architects.

    Enroll to keep reading

    Lesson 3 of 8 · AI Architect (Intermediate): Design the System

    Draw one AI assistant at every level: context, container, component, sequence, deployment, state, data model and trust boundaries, plus a checklist.

    In the rest of this lesson

    • Case files
    • Decision framework
    • Comparison of the main options
    • Failure scenarios to design for
    • Worked example
    • A diagram lint for pull requests

    Enrolling is free. It unlocks every lesson in AI Architect (Intermediate): Design the System, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments