Field guide · Agentic AI

Architecture Patterns

Software design patterns are proven answers to problems that keep coming back. Agentic AI has its own set: how to split work between models, when to let an agent loop, and how to keep the whole thing safe and affordable in a large company. These are the patterns I reach for, each with a diagram, a code sketch and the traps I’ve seen, plus how I build them on real cloud services.

AI Architecture
6
Software Architecture
1
Microsoft Azure
2

How each entry works

The page has two kinds of entry. Architecture patterns explain an idea that works anywhere. Cloud architectures build one or more of those patterns from a provider’s real services, and link back to the patterns they implement.

Architecture pattern

Everyday comparison
The same idea outside software, so it sticks.
Where it comes from
The pattern’s origin, with a source you can read.
In the agent system and in a large company
What it solves, and what changes once security, cost and governance are involved.
Step by step and code sketch
How to build it, with a short Python sketch.

Cloud architecture

Services
Every real service in the design and the role it plays.
Scenario and how it works
The problem it solves and the request flow, step by step.
Security, operations and cost
Identity, networking, monitoring and what drives the bill.
Deploy it and learn more
An infrastructure-as-code sketch and the official docs.

Every entry also has a diagram and a Be careful note on how it usually goes wrong.

How to read a diagram

  • Agent
  • Model call
  • Tool
  • Store or rubric
  • Check, gate or policy
  • Person
  • Input or output
  • Boundary (cloud or code module)
  • Main path
  • Other flow
  • Optional or on failure

Agentic AI

AI Architecture

Vendor-neutral patterns for agentic AI. They describe the idea, so they work on any cloud and any framework.

6 entries · Orchestration · Reliability · Context & Memory

01Orchestration

Prompt Chaining

Also known as: Sequential workflow, LLM pipeline

Split a task into a fixed sequence of model calls, where each step works on the output of the one before and plain code checks the result between steps.

Prompt chaining: an input passes through three model calls in a fixed order, with a code gate between each pair of steps that stops the chain early if the output so far is invalid. Inputrequest Step 1outline Gateoutline ok? Step 2draft Gatedraft ok? Step 3polish Outputresult Stop early pass pass fail fail
Fig. 01 Three model calls run in a fixed order, with a code gate between each pair of steps. A failed gate stops the chain at the step that went wrong, so a bad outline never becomes a draft and a bad draft never gets polished.

Everyday comparison

The assembly line

A car factory doesn't ask one person to build a whole car. One station fits the frame, the next adds the engine, and an inspector checks the welds before the car moves on. Each station does one job well, and a problem is caught at the station where it happened, not at the end of the line.

Where it comes from

Anthropic's Building effective agents lists it first among its workflows: each model call works on the output of the one before, with optional programmatic checks, or "gates", between the steps. It recommends it for tasks that split cleanly into fixed subtasks, trading some speed for accuracy.

In the agent system

Prompt chaining is a workflow, not an agent. The steps and their order are written in code, so the model never decides what happens next. That's the point. You trade flexibility for predictability, and each call gets a smaller, clearer job than one giant prompt would.

It fits any task that splits cleanly into stages: outline, then draft, then polish. Or extract, then classify, then summarize.

In a large company

Chains are easy to govern, which is why they're often the first pattern that gets through architecture review. Every step is a named, versioned prompt with its own input and output schema, so you can log, test and swap them one at a time.

You can also give each step the cheapest model that does the job well. The extraction step rarely needs your most expensive model.

Step by step

  1. Write down the stages the task already has. If you can't name them, this isn't the right pattern.
  2. Give each stage its own prompt with a clear input and output format.
  3. Between steps, add a gate in code that checks the output before the next step sees it. It can be a schema check, a length limit or a keyword test.
  4. When a gate fails, stop or retry that step. Don't pass bad output down the line.
  5. Log each step's input and output, so a bad result can be traced to the step that caused it.

Code sketch

def write_article(topic: str) -> str:
    outline = call_model("Write a five-point outline about: " + topic)

    # Gate: plain code, not another model call.
    points = [line for line in outline.splitlines() if line.strip()]
    if len(points) != 5:
        raise ChainStopped("outline step returned %d points" % len(points))

    draft = call_model("Write an article from this outline:\n" + outline)

    # Gate: catch a thin draft before the polish step hides it.
    words = len(draft.split())
    if words < 400:
        raise ChainStopped("draft step returned %d words" % words)

    return call_model("Tighten this draft. Keep the facts:\n" + draft)

02Orchestration

Orchestrator–Workers

Also known as: Lead agent and sub-agents, Planner–executor, Supervisor

A lead agent breaks a task into sub-tasks at run time, hands each one to a worker with its own focused context, and combines what comes back.

Orchestrator and workers: an orchestrator agent plans a task and hands sub-tasks to three worker agents, then combines their results into one answer, re-planning when the results have gaps. Taskopen-ended Orchestratorplan · delegate Worker Asearch the code Worker Bchange the files Worker Crun the tests Orchestratorsynthesize Answer re-plan when the results have gaps results
Fig. 02 The orchestrator plans and delegates to three workers, then synthesizes their results into one answer. When the results leave gaps, it plans another round.

Everyday comparison

The general contractor

When you renovate a kitchen, the contractor walks through the room, decides what needs doing and calls in an electrician, a plumber and a tiler. None of them sees the whole plan, and they don't need to. The contractor checks their work, notices the socket is in the wrong place, and sends the electrician back.

Where it comes from

Anthropic's Building effective agents describes it as the workflow for tasks where you can't predict the sub-tasks in advance. One of its examples is a coding change across several files, where which files need changing depends on the task. Multi-agent frameworks often call the same shape a supervisor.

In the agent system

The difference from prompt chaining is who decides the steps. In a chain, you write them in code. Here, the orchestrator decides them at run time, based on the task in front of it.

Each worker starts with a clean context window that holds only its sub-task. That's the real win: the orchestrator's context stays small because it gets back summaries, not every file a worker read. Independent workers can also run in parallel.

In a large company

Give each worker only the tools its job needs. A worker that searches code doesn't need write access, and a worker that edits files doesn't need the production database. The orchestrator is the one place to enforce that, so put the tool list in the hand-off, not in the worker's goodwill.

Budget the whole run, not just each call. Workers multiply cost quickly, so set a limit on workers, rounds and tokens, and log every hand-off so you can see why the orchestrator spent what it spent.

Step by step

  1. Give the orchestrator the task, the list of worker types and the tools each one may use.
  2. Have it write a plan: sub-tasks, each with a goal, boundaries and the expected answer format.
  3. Run the workers, in parallel where the sub-tasks don't depend on each other.
  4. Collect short results, not full transcripts, back into the orchestrator.
  5. Let the orchestrator check for gaps and either plan another round or write the final answer.
  6. Stop at a fixed number of rounds, even if it wants another one.

Code sketch

def orchestrate(task: str, max_rounds: int = 3) -> str:
    results = []
    for _ in range(max_rounds):
        plan = call_model(
            "Split this task into independent sub-tasks. "
            "For each, give a goal, its limits and the answer format.",
            task=task,
            done_so_far=results,
            schema=Plan,
        )
        if not plan.subtasks:
            break
        results += run_in_parallel(
            run_worker(sub, tools=TOOLS[sub.kind]) for sub in plan.subtasks
        )
    return call_model("Combine these results into one answer.", task=task, results=results)

03Orchestration

AI-SDLC

Also known as: AI-native SDLC, Agentic SDLC, Agentic software development

Agents work at every stage of software delivery, from intent to spec, plan, code, review and release, and each stage commits an artifact a person accepts before the next one starts.

AI-SDLC: a spec agent turns an intent into a spec that the owner accepts, a build agent plans, codes and tests once an engineer accepts its plan, a review agent checks the pull request and sends changes back, a code owner approves the merge, and a named person authorizes the release at the production gate; every stage commits its artifact to the repository, and when a production monitor detects a breach, an ops agent diagnoses it and writes it up as a new intent, closing the loop. Repository Intentidea · ticket Spec agentintent → spec Build agentplan · code · test Review agentreviews the PR Code ownerapproves Owneraccepts spec Engineeraccepts plan Ops agentdiagnose · intent Productionrelease gate intent · spec plan · PR findings merge release changes breach new intent: people triage it, and the loop starts again
Fig. 03 A spec agent turns an intent into a spec, which the owner accepts. The build agent plans, codes and tests once an engineer accepts its plan, a review agent checks the pull request, and only a code owner can merge it. Every artifact is committed to the repository. When monitoring detects a breach in production, an ops agent diagnoses it and writes it up as a new intent, and the loop starts again.

Everyday comparison

The building project

A client writes a brief, an architect turns it into drawings, and the client signs them. The builder works only to signed drawings and checks their own work as they go. An inspector signs off before anyone moves in. Every brief, drawing and inspection report goes into the project file, and when the roof leaks a year later, the report becomes the next brief.

Where it comes from

Anthropic's AI-native SDLC playbook starts from one observation: "Code is no longer the bottleneck." Agents can write most of the diff, but planning, review and release still move at human speed. The playbook keeps the six classic stages (plan, design, build, test, deploy, maintain) and changes how work moves between them: "Instead of a linear flow, the process becomes a loop, and AI is embedded at each point."

Its core rule is that "Every stage commits an artifact the next stage can read": an intent, a spec, a plan, the code with its tests, a pull request with review findings and, in the end, an incident record. "The chain of commits is also the audit trail: who asked for what, what the agent produced, and who approved it."

In the agent system

The stages form a workflow: each accepted artifact starts the next stage, and code enforces the gates between them. Inside each stage is a real agent. A spec agent turns an idea, ticket or alert into an intent and then a spec. The build agent reads the code and writes a plan before it changes anything, because "Nothing is implemented without an accepted plan." It then codes and checks its own work with tests, a build or a visual comparison, so what reaches a person has already passed. A separate review agent, with a fresh context, checks every pull request for bugs, security and whether it matches the spec and plan. The loop closes in production: plain code watches the service and calls an ops agent only when a metric leaves its normal range. The agent diagnoses the problem, acts only through gated routes such as a rehearsed rollback, and writes what it found as a new intent, so people triage the work instead of having to start it.

It's Orchestrator–Workers and Reflection inside the gates a human team already uses. Written instructions for the agents are advisory. The deterministic layer behind them is checks that run before the agent acts: they block edits to protected files and to the tests under repair, and they stop a production deploy without sign-off. It fits teams with a test suite and a clear owner for each decision. Without tests, the agent has nothing to check its work against.

In a large company

Separation of duties survives because the agent that wrote the code can't approve it. Branch protection turns everything an agent writes into a pull request that needs a code owner's approval, and "The agent may act up to the production gate, and cannot pass it": it prepares the release, and a named person authorizes it. Give each agent its own identity, scoped short-lived credentials and more autonomy in development than in production, so every log shows what the agent did and what a person did.

The agents' configuration is code, so test it like code. Keep a suite of 20 to 50 real tasks, run it whenever the instructions or controls change, and turn every production incident into a new case. Review capacity is the real limit: "add sessions only while review is keeping up."

Step by step

  1. Write every request as an intent (problem, outcome, constraints, open questions) and commit it.
  2. Have an agent turn the accepted intent into a spec, and let the owner accept the spec before any plan is made.
  3. Let the build agent read the code and write a plan, and don't let it change files until an engineer accepts the plan.
  4. Give the agent a way to check its own work, and block it from editing the tests it must pass.
  5. Run a review agent on every pull request, let the build agent fix its findings, and require a code owner's approval to merge.
  6. Let agents act up to the production gate and never past it, and let plain monitoring call an ops agent that writes each breach up as a new intent.

Code sketch

def deliver(intent: Intent, max_rounds: int = 3) -> Release:
    spec = call_model("Turn this intent into a spec.", intent=intent, schema=Spec)
    require_approval(commit(spec), by="owner")
    plan = run_worker(spec, tools=READ_ONLY_TOOLS, schema=Plan)
    require_approval(commit(plan), by="engineer")
    # The agent checks its own work and can't edit the tests it must pass.
    pr = run_worker(plan, tools=BUILD_TOOLS, done_when="all tests pass")
    for _ in range(max_rounds):
        findings = run_worker(pr.diff, tools=REVIEW_TOOLS, policy=REVIEW_POLICY, schema=Findings)
        if not findings.important:
            break
        pr = run_worker(findings, tools=BUILD_TOOLS, pr=pr)
    else:
        raise NeedsHumanReview(pr, findings)
    # Gates live in branch protection and the release process, not in the prompt.
    require_approval(pr, by="code_owner")
    return prepare_release(pr)  # A named person authorizes production.

04Reliability

Evaluator–Optimizer

Also known as: Generate–critique–revise, LLM-as-judge loop

One model call writes a draft, a second call checks it against clear criteria and explains what's wrong, and the draft goes back for another pass until it passes.

Evaluator and optimizer: a generator model writes a draft, an evaluator model scores it against a rubric, and the draft goes back with feedback until it passes or the round limit is reached. Rubric Task+ criteria Generatorwrite · revise Evaluatorscore · critique Outputaccepted draft pass fail: feedback goes back to the generator stops after N rounds and escalates
Fig. 04 The generator writes a draft, the evaluator scores it against a rubric, and failing drafts go back with feedback. The loop stops when a draft passes or the round limit is hit.

Everyday comparison

The writer and the editor

A journalist files a story, and the editor hands it back covered in notes: the lead is buried, the second quote isn't attributed, cut 200 words. The journalist fixes it and sends it back. Two or three rounds later it runs. The editor doesn't write the story, and the journalist doesn't decide when it's good enough.

Where it comes from

Anthropic's Building effective agents names it as the workflow for tasks with clear evaluation criteria, where feedback measurably improves the result. It builds on research such as Self-Refine, where a model improves its own output from its own feedback, and work on LLM-as-a-judge, which measured how well a strong model's verdicts match human judgement.

In the agent system

The pattern works when two things are true. You can say what "good" looks like, and a model's feedback actually makes the next draft better. Translation, code that must pass tests and documents with a strict house style are good fits. Open creative work, where "better" is a matter of taste, is not.

The evaluator can be a model, but use plain code when you can. A test suite, a linter or a schema check is cheaper, faster and never changes its mind.

In a large company

The rubric is a business artifact, not a prompt detail. Store it, version it and have the people who own the quality bar sign it off. When an output is challenged later, you can show the exact criteria it passed.

Watch the cost. Each round is at least two model calls, so measure how often the second and third rounds actually change the verdict. If round three almost never helps, stop at two.

Step by step

  1. Write the rubric: a short list of pass or fail criteria the evaluator can check.
  2. Grade a handful of drafts by hand and make sure the evaluator agrees with you.
  3. Generate a first draft.
  4. Have the evaluator return a verdict and specific feedback, in a fixed format.
  5. If it fails, send the draft and the feedback back to the generator.
  6. Stop when it passes or after a fixed number of rounds, and send anything that never passed to a person.

Code sketch

def refine(task: str, rubric: str, max_rounds: int = 3) -> str:
    draft = call_model("Complete this task:\n" + task)
    for attempt in range(1, max_rounds + 1):
        review = call_model(
            "Check the draft against the rubric. Return pass or fail, with specific fixes.",
            rubric=rubric,
            draft=draft,
            schema=Review,
        )
        if review.passed:
            return draft
        if attempt < max_rounds:
            draft = call_model("Revise the draft using this feedback:\n" + review.feedback, draft=draft)
    # Every round failed: a person decides, with the last draft and its feedback.
    raise NeedsHumanReview(draft, review.feedback)

05Reliability

Reflection

Also known as: Reflexion, Self-reflection, Self-correction

After a failed attempt, the agent works out what went wrong, writes itself a short lesson, and tries again with that lesson in hand, so each attempt learns from the last.

Reflection: an actor attempts the task, an evaluator checks the attempt with tests or tools, and a failed attempt goes to a reflector that writes a short lesson into memory, which the actor reads on its next try, until an attempt passes or the attempt limit is reached. Tools Task+ success test Actorattempt · act Evaluatortests · tools Outputpassed Lessonslast few kept Reflectorwhy it failed attempt pass fail lesson next try stops after N attempts and escalates
Fig. 05 The actor attempts the task and an evaluator checks the result with tests or tools. A failed attempt goes to the reflector, which writes a short lesson into memory, and the actor reads it on the next try. The loop stops when an attempt passes or the attempt limit is hit.

Everyday comparison

The driving test

A learner fails a driving test, and the examiner's sheet says why: no mirror check before the roundabout, too fast into the bend. That evening the learner writes two lines on a card: check the mirror before every roundabout, brake before the bend, not in it. The card goes into their pocket for the next test. The examiner never teaches, and the learner doesn't replay the whole drive, only the lessons on the card.

Where it comes from

Three 2023 papers shaped the pattern. Self-Refine has one model write an answer, critique it and rewrite it, with no extra training, and reports about 20% absolute improvement on average across seven tasks. It also showed where self-critique breaks: on math problems the model couldn't tell whether its own answer had an error, so the gains were small. Reflexion added memory across attempts. After a failure the agent writes a short reflection, keeps the last one to three, and reads them on its next try. With unit tests it wrote itself as the signal, it reached 91% pass@1 on the HumanEval coding benchmark, against 80% for GPT-4 on its own.

CRITIC looked at what the critique should rest on. It checks each answer with tools, such as a search engine for facts or a code interpreter for code, before correcting it. Its authors found that self-correction without outside feedback "may yield modest improvements or even deteriorate performance."

In the agent system

The loop around the attempts is a workflow: code runs the attempt, checks it, asks for a reflection and decides whether to try again. The attempt itself is often an agent with tools, as in Reflexion. The difference from Evaluator–Optimizer is what carries over between rounds. There, an evaluator marks up one draft until it passes. Here, the agent explains its own failure in words and takes that lesson into a fresh attempt. That helps most on multi-step tasks, where the fix is a different approach, not a better sentence.

It fits when a failure produces a clear signal: tests fail, a tool returns an error, an answer contradicts a search result. It fits poorly when the only judge is the model's opinion of itself, and it doesn't help much on tasks that need broad exploration. Reflexion made no real progress on a web-shopping benchmark where the agent had to search widely. It also needs a capable model: in both Self-Refine and Reflexion, smaller open models didn't produce feedback that helped.

In a large company

Lessons are data the agent writes for itself, so govern them like any other memory. Log every reflection next to the attempt that caused it, and scope lessons to the task or customer they came from, so one client's case never shapes another's. Because reflections are plain text, the Reflexion authors note they can be checked before the agent acts on them. A trail of written lessons is far easier to audit than a model's hidden reasoning.

Cost and risk grow with every attempt. Each retry is a full attempt plus a reflection call, so measure how often attempts two and three actually succeed and set the limit from that. If attempts run generated code, run it in a sandbox: the Reflexion authors advise isolated execution environments because the code isn't validated before it runs.

Step by step

  1. Choose the outside signal that decides success: tests, a tool check or a policy rule, not the model's opinion of its own work.
  2. Run the attempt and keep its trajectory: the actions, the tool results and the final answer.
  3. If the check fails, ask the model to say in two or three sentences what went wrong and what to do differently.
  4. Store that lesson, keep only the last few, and give them to the next attempt.
  5. Test the signal itself, because a self-written test that passes a wrong answer ends the loop with a confident mistake.
  6. Stop after a fixed number of attempts and send anything that never passed to a person, with its lessons.

Code sketch

def reflect_and_retry(task: str, max_rounds: int = 3) -> str:
    lessons: list[str] = []
    for _ in range(max_rounds):
        attempt = run_worker(task, tools=TOOLS, lessons=lessons)
        # The verdict comes from tests or tools, not the model's view of itself.
        verdict = run_checks(task, attempt)
        if verdict.passed:
            return attempt.answer
        lesson = call_model(
            "Your attempt failed. In two or three sentences, say why and what to do differently.",
            task=task,
            trajectory=attempt.trajectory,
            feedback=verdict.details,
        )
        # Keep only the latest few lessons, as Reflexion does.
        lessons = (lessons + [lesson])[-3:]
    raise NeedsHumanReview(attempt.answer, lessons)

06Context & Memory

Retrieval-Augmented Generation

Also known as: RAG, RAG chatbot, Grounded generation

Before the model answers, code searches your own documents for the passages that matter and puts them in the prompt, so the answer rests on your data instead of the model's memory.

Retrieval-augmented generation: a question goes to a retriever that pulls passages from an index, a model answers from those passages, and a check releases the answer only if it is grounded, otherwise the system declines. Index Question+ user rights Retrieversearch · filter Generatoranswer · cite Checkgrounded? Answerwith sources Decline top passages pass not grounded
Fig. 06 The question goes to a retriever, which pulls the best passages from an index. The model answers from those passages, and a check sends the answer out only if it is grounded in them.

Everyday comparison

The open-book exam

In an open-book exam, nobody expects you to remember every fact. You find the right page, read it, and write your answer from it, citing the page. A student who picks the wrong chapter still writes a confident answer, just a wrong one. The grade depends on finding the page as much as on writing well.

Where it comes from

The name comes from the 2020 paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks by Patrick Lewis and colleagues, which paired a language model with a search index over Wikipedia so answers could draw on facts the model didn't store. Anthropic's Building effective agents treats retrieval as part of the basic building block of agentic systems: "an LLM enhanced with augmentations such as retrieval, tools, and memory."

In the agent system

In its simplest form it is a workflow: code always searches, then the model answers. In an agent, search is a tool, and the model decides when to call it and what to search for, sometimes several times. Start with the workflow. Move to the agent version only when one search per question isn't enough.

It fits when the answer lives in documents you own and change: policies, product manuals, contracts, tickets. It doesn't fix a model that can't reason about the material, and it isn't the right tool when the data is structured and a database query would give the exact answer.

In a large company

Access control is the hard part. The index must respect who is allowed to read each document, so filter results by the user's permissions at query time, not by asking the model to hide what it shouldn't show.

Treat the index as a product with an owner. Documents go stale, get duplicated and contradict each other. Decide who keeps the sources clean, how often the index refreshes, and log which passages each answer used, so a wrong answer can be traced back to its source.

Step by step

  1. Split your documents into passages and index them, keeping the source and access rights on every passage.
  2. Build a test set of real questions with the passages that should answer them, and measure retrieval on it before you tune any prompt.
  3. At question time, search the index, filtered by the user's permissions, and keep the top few passages.
  4. Ask the model to answer only from those passages and to cite them.
  5. Check the answer against the passages before it goes out.
  6. If nothing relevant comes back or the check fails, say you don't know instead of guessing.

Code sketch

def answer(question: str, user: User, top_k: int = 5) -> Answer:
    passages = search_index(question, allowed_for=user, limit=top_k)
    if not passages:
        # Nothing to ground on: decline instead of guessing.
        return Answer.not_found()
    reply = call_model(
        "Answer only from the passages. Cite each one you use.",
        question=question,
        passages=passages,
        schema=Answer,
    )
    check = call_model("Is every claim supported by the passages?", reply=reply, passages=passages, schema=Verdict)
    if not check.grounded:
        return Answer.not_found()
    return reply

App Development

Software Architecture

Vendor-neutral patterns for structuring the code behind an application, agentic or not: how features, modules and shared code are organised.

1 entry · Application Structure

SA-01Application Structure

Vertical Slice Architecture

Also known as: Feature slices, Feature folders, Slice architecture

Organise code by feature instead of by technical layer, so everything one request needs, from the endpoint to the data, lives together in one folder.

Vertical Slice Architecture: two feature folders, add_task and complete_task, each hold their own endpoint, request schema and handler, and a request runs through only its own slice before both slices write to a shared task store. features/add_task/ features/complete_task/ EndpointPOST /tasks Schemaname not blank Handlersave the task EndpointPATCH /tasks/{id} Schemacompleted = true Handlermark complete Tasksshared store
Fig. SA-01 Two slices, add_task and complete_task, each hold their own endpoint, request schema and handler. A request enters one slice, its schema validates it and its handler does the work, and the only thing the slices share is the task store. main.py only registers each slice's router.

Everyday comparison

The meal kit

A meal kit doesn't send you a bag of all the onions, a bag of all the spices and a bag of all the sauces for the week. Each box holds everything for one recipe: the card, the measured ingredients, the sauce. To cook Tuesday's dinner you open one box and nothing else. A new recipe is a new box, and the other boxes stay exactly as they were. Salt and oil still come from the shared shelf.

Where it comes from

Jimmy Bogard, who also wrote the MediatR library for .NET, named it in his 2018 post Vertical Slice Architecture. He builds each system around distinct requests, grouping everything one request needs "from front-end to back", and couples "along the axis of change" instead of across layers. His rule: "Minimize coupling between slices, and maximize coupling in a slice."

He came to it after an onion architecture project started to crack within months. His argument is that rigid layer rules, like "Controller MUST talk to a Service that MUST use a Repository", add abstractions most requests don't need. Each slice can choose its own approach instead: start with simple code and refactor only when it grows complex.

In the agent system

Vertical slices are neither a workflow nor an agent. They are a way to lay out the code that hosts both. In an agentic app, each capability is one slice: "draft a reply", "summarise a ticket" and "search the policy docs" each get a folder with their own endpoint or tool definition, input schema, prompt, model call and eval cases. Changing one prompt touches one folder, and only that slice's evals need to run again. The same holds for agent tools: one tool is one slice, and an MCP server registers its tools the way main.py registers routers.

The alternative is the familiar layered layout: a prompts/ folder, a services/ folder and a repositories/ folder, where every feature is spread across all three. That works for a small app with a handful of endpoints. It also stops paying off when slices share a lot of real domain rules, which then belong in a shared domain model. Bogard's own caveat: the team has to recognise when a handler is doing too much and refactor it.

In a large company

Slices make ownership clear. A team owns a feature folder end to end, review rules can be set per folder, and deleting a feature means deleting a folder rather than hunting through layers. It is also easier to audit: each slice declares which tools, data and model it uses, so least-privilege access and cost per feature can be checked one slice at a time.

The risk at scale is that every team solves the same cross-cutting problems on its own. Keep authentication, logging, tracing, rate limits and the model gateway in shared middleware that every slice passes through, so slices hold business logic, not copies of plumbing.

Step by step

  1. List the requests the system handles, one use case per line, and give each its own folder under features/.
  2. Put that use case's endpoint, request schema and handler in its folder, and nothing that belongs to another use case.
  3. Register every slice's router or tool in one entry point, so that file is the only one that knows about all the slices.
  4. Write each handler as the simplest code that does the job, and refactor it into domain objects only when the logic grows complex.
  5. Keep cross-cutting concerns such as authentication, logging and tracing in shared middleware instead of copying them into each slice.
  6. Never import from one slice into another. When a business rule repeats, move it into shared domain code.

Code sketch

# features/add_task/schema.py: the request this slice accepts.
class AddTask(BaseModel):
    name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]

# features/add_task/handler.py: the operation, as simple as it can be.
def add_task(request: AddTask, db: Database) -> Task:
    return db.tasks.insert(Task(name=request.name, completed=False))

# features/add_task/router.py: the endpoint.
router = APIRouter()

@router.post("/tasks", status_code=201)
def post_task(request: AddTask, db: Database = Depends(get_db)) -> Task:
    return add_task(request, db)

# main.py: the only file that knows about every slice.
app = FastAPI()
app.include_router(add_task.router)
app.include_router(complete_task.router)

Cloud

Microsoft Azure

Reference architectures built from real Azure services. Each one implements one or more of the generic patterns above.

2 entries · AI Agents

AZ-01AzureAI Agents

Multi-Agent Orchestration on Azure

Also known as: Orchestrator–Workers on Azure, Agent Framework on Container Apps

An orchestrator and its worker agents run as your own code on Azure Container Apps, reach Foundry models through an API Management AI gateway, and keep plans and results in Cosmos DB.

Multi-agent orchestration on Azure: a user submits a task through App Service; an orchestrator agent on Azure Container Apps fans it out to three worker agents, which call Foundry models through API Management, while the orchestrator saves plans and state in Cosmos DB. Azure subscription Container Apps User App Servicefront end Orchestratorplan · combine Worker Aresearch Worker Bact Worker Ccheck Foundrymodel deployments API ManagementAI gateway Cosmos DBplans · state every model call saves state
Fig. AZ-01 A user submits a task through App Service. The orchestrator on Container Apps fans it out to three workers, every model call goes through API Management to Foundry, and the orchestrator saves plans and state in Cosmos DB.

Azure services

ServiceRole in this architecture
Azure App ServiceHosts the front end where users submit tasks and follow their progress.
Azure Container AppsRuns the orchestrator and worker agents, written with Microsoft Agent Framework.
Microsoft FoundryHosts the model deployments that every agent calls.
Azure API ManagementAI gateway between the agents and Foundry, with token limits, load balancing and usage logs per agent.
Azure Cosmos DBStores plans, task state and agent outcomes, so runs can resume and be audited.
Microsoft Entra IDManaged identities, so no service holds a key for another.
Application InsightsTraces each run across the orchestrator and its workers.

Scenario

A team wants agents to handle multi-step requests: research a supplier, draft a contract change, check it against policy. One agent with every tool gets confused and expensive, so the work is split between an orchestrator and specialist workers, as in the generic Orchestrator–Workers pattern.

This design follows Microsoft's multi-agent reference architecture, where the agents are your own code rather than managed agents. On top of it, I add an AI gateway, managed identities and tracing, which a large company will ask for before go-live.

How it works

  1. The user submits a task in the web front end on App Service.
  2. The orchestrator, a Microsoft Agent Framework app on Container Apps, asks a model to break the task into sub-tasks and saves the plan in Cosmos DB.
  3. It hands each sub-task to a worker agent in the same Container Apps environment. Independent workers run in parallel.
  4. Every model call, from the orchestrator or a worker, goes to API Management, which applies the agent's token limit and forwards the call to a Foundry model deployment.
  5. Workers return short results. The orchestrator stores them, checks for gaps, and either plans another round or writes the final answer.
  6. The front end reads the run's status and result from Cosmos DB.

Security and identity

  • Each Container App runs as its own managed identity. API Management authenticates to Foundry with its own managed identity, so no agent holds a model key.
  • Give each worker identity access only to the tools and data its job needs, and keep that list in code review, not in a prompt.
  • Run the Container Apps environment in a virtual network, reach Foundry and Cosmos DB through private endpoints with public access turned off, and let traffic in only through the front end and the gateway.

Reliability and operations

  • Because the plan and every result are in Cosmos DB, a crashed orchestrator can resume a run instead of starting over.
  • API Management can spread calls across several Foundry deployments and fail over when one is throttled.
  • Trace every run with OpenTelemetry into Application Insights, with one trace spanning the orchestrator and its workers, so a slow or failing worker is easy to find.

Cost

  • Model tokens are almost always the biggest cost, and fan-out multiplies them. Measure tokens per completed task, not per call.
  • The gateway's token limits per agent cap the worst case. Its usage logs show which agent spends what.
  • Container Apps can scale idle workers to zero, so the compute cost follows real usage.

Deploy it

A Bicep sketch of the one piece people most often get wrong: letting the gateway call Foundry with its managed identity instead of a key. It is a sketch, not a full deployment.

param foundryName string
param apimName string
@description('Role that allows calling Foundry models, as listed in the Foundry docs')
param modelUserRoleId string

resource foundry 'Microsoft.CognitiveServices/accounts@2024-10-01' existing = {
  name: foundryName
}

resource apim 'Microsoft.ApiManagement/service@2023-05-01-preview' existing = {
  name: apimName
}

// Keyless: only the gateway's identity may call the models.
resource gatewayModelAccess 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  scope: foundry
  name: guid(foundry.id, apim.id, modelUserRoleId)
  properties: {
    principalId: apim.identity.principalId
    principalType: 'ServicePrincipal'
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', modelUserRoleId)
  }
}

Learn more

AZ-02AzureAI Agents

Enterprise Chatbot on Azure

Also known as: Baseline Foundry Chat on Azure, Retrieval-Augmented Generation on Azure

A chat front end on App Service, behind Application Gateway and its WAF, talks to a Foundry Agent Service agent that grounds answers in AI Search and keeps conversations in Cosmos DB, all on private networking.

Enterprise chatbot on Azure: a user reaches the chat UI on App Service through Application Gateway; a Foundry agent in the virtual network grounds its answer in AI Search, calls a Foundry model and saves the conversation in Cosmos DB over private endpoints, while calls to public tools leave through Azure Firewall. Azure subscription Virtual network User Public tools App GatewayWAF · TLS App Servicechat UI Foundry Agentground · answer Firewallegress rules Foundrychat model AI Searchgrounding index Cosmos DBconversations public tool calls only via private endpoints
Fig. AZ-02 A user reaches the chat UI on App Service through Application Gateway. The Foundry agent grounds its answer in AI Search, calls a Foundry model and saves the conversation in Cosmos DB over private endpoints, and any call to a public tool leaves through Azure Firewall.

Azure services

ServiceRole in this architecture
Azure Application GatewayThe only public entry point, terminating TLS and inspecting every request with Azure Web Application Firewall.
Azure App ServiceHosts the chat UI and the server code that signs users in, checks conversation ownership and calls the agent.
Foundry Agent ServiceRuns the chat agent in the standard setup, injected into your virtual network, with its instructions, model and tools.
Microsoft FoundryHosts the model deployment the agent calls, with a content filter bound to it.
Azure AI SearchHolds the grounding index the agent searches before it answers.
Azure Cosmos DB for NoSQLStores conversations and agent definitions in your subscription, so chats can resume.
Azure StorageHolds files users upload in chat.
Azure FirewallControls all outbound traffic from the agent with FQDN rules, so it can reach only the public tools you allow.
Azure Private LinkPrivate endpoints for Foundry, AI Search, Cosmos DB and Storage, with public access turned off.
Azure Key VaultStores the TLS certificate for Application Gateway, the only secret in the design.
Microsoft Entra IDSigns users in and gives every service a managed identity, so nothing holds a key.
Application InsightsTraces each chat turn from the web app through the agent and its tool calls.

Scenario

A company wants an internal assistant that answers questions from its own policies, manuals and knowledge base, and it has to pass a security review before anyone outside the pilot team sees it. That is Retrieval-Augmented Generation with one agent, wrapped in the network controls, identities and monitoring a production workload needs.

This design follows Microsoft's Baseline Microsoft Foundry Chat reference architecture: Application Gateway in front, App Service for the UI, Foundry Agent Service in the standard setup with your own Cosmos DB, Storage and AI Search, and egress through Azure Firewall. On top of it, I add two things: a retrieval test set that runs before every agent or index change ships, and a token budget per user with an alert, so a pilot can't quietly become the biggest line on the bill.

How it works

  1. The user opens the chat UI. The request reaches Application Gateway, where the WAF inspects it before it reaches App Service.
  2. The App Service app signs the user in, checks that they own the conversation, and calls the Foundry agent over a private endpoint with its managed identity.
  3. The Foundry agent applies its instructions and searches AI Search over a private endpoint for the passages that ground its answer.
  4. It calls its Foundry model with the question and those passages. The content filter on the deployment screens both.
  5. Calls to public tools, such as web search or a public API, leave only through Azure Firewall. Calls to private tools stay in the virtual network.
  6. Before replying, the agent saves the turn in Cosmos DB, and the answer goes back to the user through App Service.

Security and identity

  • Every component has its own managed identity, and connections use Microsoft Entra ID. The web app needs the Foundry User role to call the agent, and no service holds a key.
  • Foundry Agent Service doesn't enforce per-user access to conversations, so the web app must check ownership on every request. Without it, one user can read another's chat.
  • Only Application Gateway has a public IP. Foundry, AI Search, Cosmos DB and Storage are reached through private endpoints with public access off, and the agent's outbound traffic is forced through Azure Firewall.
  • Filter AI Search results by the signed-in user's permissions when documents aren't open to everyone in the company.

Reliability and operations

  • Deploy App Service, Application Gateway, Cosmos DB, Storage, AI Search and Azure Firewall across availability zones. AI Search needs at least three replicas for zone redundancy.
  • Foundry Agent Service has no built-in disaster recovery: it can't replicate, back up or restore its state. If you need another region, plan the failover yourself, including the Cosmos DB, Storage and AI Search behind it.
  • Define the agent as code, pin the agent and model versions, and run the retrieval test set and a regression set of conversations in your pipeline before each release.
  • Send traces from the web app and the agent to Application Insights, so a slow answer can be traced to search, the model or a tool.

Cost

  • Model tokens drive the bill, and retrieved passages are input tokens on every turn. Keep the number and size of passages small, and measure tokens per answered question.
  • The fixed cost is the platform: Application Gateway with WAF, Azure Firewall, zone-redundant AI Search and Cosmos DB run all month, even when nobody chats. Size them to the real load and use reserved capacity once usage is stable.
  • Connect only the tools most conversations need, and delete old agents and conversations you no longer have to keep.

Deploy it

A Bicep sketch of the piece people most often get wrong: letting the web app call the agent with its managed identity instead of a key. It is a sketch, not a full deployment.

param foundryName string
param webAppName string
@description('ID of the Foundry User role, as listed in the Foundry RBAC docs')
param foundryUserRoleId string

resource foundry 'Microsoft.CognitiveServices/accounts@2024-10-01' existing = {
  name: foundryName
}

resource webApp 'Microsoft.Web/sites@2023-12-01' existing = {
  name: webAppName
}

// Keyless: the chat web app calls the agent as itself.
resource webAppAgentAccess 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  scope: foundry
  name: guid(foundry.id, webApp.id, foundryUserRoleId)
  properties: {
    principalId: webApp.identity.principalId
    principalType: 'ServicePrincipal'
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', foundryUserRoleId)
  }
}

Learn more