›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Architecture Patterns in Practice

Organizing the Code: Modular Monolith, Clean Architecture and Vertical Slices, with Runnable C# and Python

September 30, 2026 · 20 min read

Software Architecture, Design Patterns, C#, Python, Modular Monolith, Clean Architecture, Vertical Slice

This post is part of Architecture Patterns in Practice, a series that puts runnable code behind the patterns in my architecture patterns map for 2026. This first post covers the question that's most expensive to get wrong late: how is the code organized?

There are three patterns here, and they aren't rivals. A modular monolith decides where the walls go between big areas of the system. Layered or clean architecture decides which way dependencies point inside one area. Vertical slices decide whether you group code by technical layer or by feature. Many healthy codebases use all three: modules at the top, slices inside each module, and clean dependency rules inside the slices that have real business logic.

PatternThe question it answersGoF idea underneath
Modular monolithWhere are the walls between parts of the system?Facade (each module's public API)
Layered / cleanWhich way do dependencies point?Adapter, plus dependency inversion
Vertical sliceDo I group code by layer or by feature?Command and Mediator

Every snippet below is complete and runs as is. The C# files are .NET 10 file-based apps (dotnet run file.cs), and the Python files need only the standard library.

Modular monolith

The problem. A single deployable is the right way to start. Martin Fowler's "monolith first" advice still holds. But as the codebase grows, everything starts touching everything. The orders code reads the inventory tables directly, the billing code calls a private helper in shipping, and soon nobody can change one area without breaking another. The usual reaction is to split into microservices. That trades a code problem for a network problem.

The pattern. Keep one deployable, but split it into modules with hard boundaries. Each module owns its data and exposes a small public contract. Other modules may only use that contract. The boundary is enforced by a check that fails the build, not by good intentions.

In C#, the ideal is one project per module, with the implementation marked internal. To keep this runnable as a single file, I've used namespaces instead, with an architecture test that does what the compiler would do across projects:

#:property PublishAot=false
using System.Reflection;

// Composition root: each module registers itself; modules only see each other's contracts.
var inventory = Inventory.InventoryModule.Create(new() { ["SKU-1"] = 5, ["SKU-2"] = 0 });
var orders = Orders.OrdersModule.Create(inventory);

Console.WriteLine(orders.PlaceOrder("SKU-1", 2));
Console.WriteLine(orders.PlaceOrder("SKU-2", 1));
Console.WriteLine($"SKU-1 left: {inventory.Available("SKU-1")}");

// An architecture test: no type in one module may touch another module's Internal namespace.
foreach (var v in BoundaryCheck.Violations(typeof(Program).Assembly, ["Orders", "Inventory"]))
    Console.WriteLine($"BOUNDARY VIOLATION: {v}");

namespace Inventory.Contracts
{
    // The module's front door. Other modules depend on this, never on Internal.
    public interface IInventoryApi
    {
        bool TryReserve(string sku, int quantity);
        int Available(string sku);
    }
}

namespace Inventory
{
    public static class InventoryModule
    {
        public static Contracts.IInventoryApi Create(Dictionary<string, int> stock) =>
            new Internal.InventoryService(new Internal.StockTable(stock));
    }
}

namespace Inventory.Internal
{
    sealed class StockTable(Dictionary<string, int> rows)
    {
        public Dictionary<string, int> Rows { get; } = rows;  // Inventory's own tables
    }

    sealed class InventoryService(StockTable table) : Contracts.IInventoryApi
    {
        public bool TryReserve(string sku, int quantity)
        {
            if (table.Rows.GetValueOrDefault(sku) < quantity) return false;
            table.Rows[sku] -= quantity;
            return true;
        }
        public int Available(string sku) => table.Rows.GetValueOrDefault(sku);
    }
}

namespace Orders.Contracts
{
    public interface IOrdersApi { string PlaceOrder(string sku, int quantity); }
}

namespace Orders
{
    public static class OrdersModule
    {
        public static Contracts.IOrdersApi Create(Inventory.Contracts.IInventoryApi inventory) =>
            new Internal.OrderService(inventory);
    }
}

namespace Orders.Internal
{
    sealed class OrderService(Inventory.Contracts.IInventoryApi inventory) : Contracts.IOrdersApi
    {
        private int _next = 1;
        public string PlaceOrder(string sku, int quantity) =>
            inventory.TryReserve(sku, quantity)
                ? $"order {_next++} placed: {quantity} x {sku}"
                : $"rejected: {sku} out of stock";
    }

    // A shortcut someone took: reading Inventory's table directly.
    sealed class StockReport(Inventory.Internal.StockTable table)
    {
        public int Total => table.Rows.Values.Sum();
    }
}

static class BoundaryCheck
{
    // Real projects use NetArchTest or ArchUnitNET; this is the idea in a dozen lines.
    public static IEnumerable<string> Violations(Assembly assembly, string[] modules)
    {
        string? ModuleOf(Type t) => modules.FirstOrDefault(m => t.Namespace?.StartsWith(m) == true);

        foreach (var type in assembly.GetTypes())
        {
            if (ModuleOf(type) is not { } owner) continue;
            var deps = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                .SelectMany(c => c.GetParameters()).Select(p => p.ParameterType).Distinct();
            foreach (var dep in deps)
                if (ModuleOf(dep) is { } other && other != owner && dep.Namespace == other + ".Internal")
                    yield return $"{type.FullName} -> {dep.FullName}";
        }
    }
}
order 1 placed: 2 x SKU-1
rejected: SKU-2 out of stock
SKU-1 left: 3
BOUNDARY VIOLATION: Orders.Internal.StockReport -> Inventory.Internal.StockTable

(The #:property PublishAot=false line only silences trimming warnings about reflection. File-based apps turn on native AOT analysis by default.)

The orders module works through IInventoryApi, and the check catches the one class that reached around it. In a real solution, make that loop an xUnit test so the build goes red. If Inventory moves to its own service one day, IInventoryApi becomes an HTTP client and nothing in Orders changes. That's the real payoff: the expensive split stays optional.

Python has no internal keyword, so the convention is a leading underscore plus a check in CI. The layout:

shop/
  inventory/
    __init__.py      # public API
    _internal.py     # private: other modules must not import this
  orders/
    __init__.py
    _internal.py
    report.py        # the shortcut someone took
main.py
check_boundaries.py

The module's __init__.py is its front door:

# shop/inventory/__init__.py
# The module's public API. Other modules import from here, never from _internal.
from shop.inventory._internal import InventoryService

__all__ = ["InventoryService"]
# shop/inventory/_internal.py
class InventoryService:
    def __init__(self, stock: dict[str, int]):
        self._stock = stock  # Inventory's own tables

    def try_reserve(self, sku: str, quantity: int) -> bool:
        if self._stock.get(sku, 0) < quantity:
            return False
        self._stock[sku] -= quantity
        return True

    def available(self, sku: str) -> int:
        return self._stock.get(sku, 0)
# shop/orders/_internal.py
from shop.inventory import InventoryService  # fine: the public API


class OrderService:
    def __init__(self, inventory: InventoryService):
        self._inventory = inventory
        self._next = 1

    def place_order(self, sku: str, quantity: int) -> str:
        if not self._inventory.try_reserve(sku, quantity):
            return f"rejected: {sku} out of stock"
        order_id, self._next = self._next, self._next + 1
        return f"order {order_id} placed: {quantity} x {sku}"
# shop/orders/report.py
from shop.inventory._internal import InventoryService  # a shortcut someone took

shop/orders/__init__.py re-exports OrderService the same way, and main.py wires the two together:

# main.py
from shop.inventory import InventoryService
from shop.orders import OrderService

inventory = InventoryService({"SKU-1": 5, "SKU-2": 0})
orders = OrderService(inventory)
print(orders.place_order("SKU-1", 2))
print(orders.place_order("SKU-2", 1))
print("SKU-1 left:", inventory.available("SKU-1"))
order 1 placed: 2 x SKU-1
rejected: SKU-2 out of stock
SKU-1 left: 3

And the boundary check, using ast so it reads imports without running any code:

# check_boundaries.py
"""Fail the build if one module imports another module's private parts."""
import ast
import pathlib
import sys

ROOT = pathlib.Path("shop")
MODULES = {p.name for p in ROOT.iterdir() if p.is_dir()}


def violations():
    for path in sorted(ROOT.rglob("*.py")):
        parts = path.relative_to(ROOT).parts
        owner = parts[0] if len(parts) > 1 else None
        for node in ast.walk(ast.parse(path.read_text())):
            if isinstance(node, ast.ImportFrom) and node.module:
                target = node.module.split(".")  # e.g. shop.inventory._internal
                if len(target) > 2 and target[1] in MODULES and target[1] != owner:
                    yield f"{path}: imports {node.module}"


found = list(violations())
for v in found:
    print("BOUNDARY VIOLATION:", v)
sys.exit(1 if found else 0)
BOUNDARY VIOLATION: shop/orders/report.py: imports shop.inventory._internal

It exits with code 1, so CI fails. For a real project, Import Linter does this with a config file and handles the cases this sketch skips, like plain import x.y statements.

The GoF pattern underneath. Each module's public API is a Facade: one small interface in front of a subsystem, so callers don't depend on its insides. I covered Facade in Adapter, Facade and Proxy. A modular monolith is that idea applied at the scale of a whole team's code.

When not to use it. If the app is small and one person or one small team owns all of it, module boundaries are ceremony. You'll spend time designing contracts between parts that change together anyway. The other trap is drawing the walls too early, before you know where the real seams are. Wrong boundaries are worse than none, because every feature then crosses two modules. My rule of thumb: start with folders, and promote a folder to a module when you notice that changes to it rarely need changes elsewhere.

Layered and clean architecture

The problem. Business rules get tangled with the framework and the database. The rule "you can't overpay an invoice" lives inside a controller action, next to the SQL. To test the rule you need a web server and a database. To change the database you rewrite the rule.

The pattern. Classic layering splits the code into UI, business logic and data access, with each layer calling the one below. Its weakness, as Microsoft's architecture guide points out, is that the business layer ends up depending on the data access layer. Clean architecture (also called hexagonal, or ports and adapters, or onion) fixes that with one rule: dependencies point inward. The domain sits in the middle and knows nothing about the outside. The application layer defines the interfaces it needs (the ports). Infrastructure on the outside implements them (the adapters). Only the composition root at startup knows every concrete type.

// Composition root (the outermost ring): the only place that knows every concrete type.
var repo = new InMemoryInvoiceRepository();
repo.Save(new Invoice("INV-1", 120m));
var payInvoice = new PayInvoice(repo, new ConsoleReceiptSender());

Console.WriteLine(payInvoice.Handle("INV-1", 100m));
Console.WriteLine(payInvoice.Handle("INV-1", 50m));
Console.WriteLine(payInvoice.Handle("INV-1", 20m));
Console.WriteLine(payInvoice.Handle("INV-9", 10m));

// ---- Domain: business rules, no framework, no I/O ----
sealed class Invoice(string id, decimal total)
{
    public string Id { get; } = id;
    public decimal Total { get; } = total;
    public decimal Paid { get; private set; }
    public bool IsSettled => Paid == Total;

    public void Pay(decimal amount)
    {
        if (amount <= 0) throw new InvalidOperationException("amount must be positive");
        if (Paid + amount > Total) throw new InvalidOperationException($"overpayment: {Total - Paid} outstanding");
        Paid += amount;
    }
}

// ---- Application: use cases + the ports they need (interfaces owned by the inner ring) ----
interface IInvoiceRepository { Invoice? Find(string id); void Save(Invoice invoice); }
interface IReceiptSender { void Send(Invoice invoice); }

sealed class PayInvoice(IInvoiceRepository invoices, IReceiptSender receipts)
{
    public string Handle(string invoiceId, decimal amount)
    {
        var invoice = invoices.Find(invoiceId);
        if (invoice is null) return $"{invoiceId}: not found";
        try { invoice.Pay(amount); }
        catch (InvalidOperationException e) { return $"{invoiceId}: rejected, {e.Message}"; }
        invoices.Save(invoice);
        if (invoice.IsSettled) receipts.Send(invoice);
        return $"{invoiceId}: paid {amount}, {invoice.Total - invoice.Paid} left";
    }
}

// ---- Infrastructure: adapters that implement the ports (swap for SQL, email, etc.) ----
sealed class InMemoryInvoiceRepository : IInvoiceRepository
{
    private readonly Dictionary<string, Invoice> _rows = [];
    public Invoice? Find(string id) => _rows.GetValueOrDefault(id);
    public void Save(Invoice invoice) => _rows[invoice.Id] = invoice;
}

sealed class ConsoleReceiptSender : IReceiptSender
{
    public void Send(Invoice invoice) => Console.WriteLine($"  [receipt] {invoice.Id} settled");
}
INV-1: paid 100, 20 left
INV-1: rejected, overpayment: 20 outstanding
  [receipt] INV-1 settled
INV-1: paid 20, 0 left
INV-9: not found

The detail that matters most: IInvoiceRepository is declared next to the use case, not next to the database code. The inner ring owns the interface, and the outer ring conforms to it. That's what "dependencies point inward" means in practice. In a real solution, these sections become separate projects (Domain, Application, Infrastructure, Web), and the project references enforce the direction for you.

The Python version uses Protocol for the ports, and shows the payoff: a test that needs no database and no mail server.

from dataclasses import dataclass
from decimal import Decimal
from typing import Protocol


# ---- Domain ----
class PaymentRejected(Exception):
    pass


@dataclass
class Invoice:
    id: str
    total: Decimal
    paid: Decimal = Decimal(0)

    @property
    def settled(self) -> bool:
        return self.paid == self.total

    def pay(self, amount: Decimal) -> None:
        if amount <= 0:
            raise PaymentRejected("amount must be positive")
        if self.paid + amount > self.total:
            raise PaymentRejected(f"overpayment: {self.total - self.paid} outstanding")
        self.paid += amount


# ---- Application: use case + ports ----
class InvoiceRepository(Protocol):
    def find(self, invoice_id: str) -> Invoice | None: ...
    def save(self, invoice: Invoice) -> None: ...


class ReceiptSender(Protocol):
    def send(self, invoice: Invoice) -> None: ...


class PayInvoice:
    def __init__(self, invoices: InvoiceRepository, receipts: ReceiptSender):
        self._invoices, self._receipts = invoices, receipts

    def handle(self, invoice_id: str, amount: Decimal) -> str:
        invoice = self._invoices.find(invoice_id)
        if invoice is None:
            return f"{invoice_id}: not found"
        try:
            invoice.pay(amount)
        except PaymentRejected as e:
            return f"{invoice_id}: rejected, {e}"
        self._invoices.save(invoice)
        if invoice.settled:
            self._receipts.send(invoice)
        return f"{invoice_id}: paid {amount}, {invoice.total - invoice.paid} left"


# ---- Infrastructure: adapters ----
class InMemoryInvoices:
    def __init__(self):
        self._rows: dict[str, Invoice] = {}

    def find(self, invoice_id):
        return self._rows.get(invoice_id)

    def save(self, invoice):
        self._rows[invoice.id] = invoice


class RecordingReceipts:  # a test double: no SMTP server needed
    def __init__(self):
        self.sent: list[str] = []

    def send(self, invoice):
        self.sent.append(invoice.id)


# ---- A test, which is the real payoff ----
repo, receipts = InMemoryInvoices(), RecordingReceipts()
repo.save(Invoice("INV-1", Decimal("120")))
use_case = PayInvoice(repo, receipts)

print(use_case.handle("INV-1", Decimal("100")))
print(use_case.handle("INV-1", Decimal("50")))
print(use_case.handle("INV-1", Decimal("20")))
assert receipts.sent == ["INV-1"], receipts.sent
print("receipts sent:", receipts.sent)
INV-1: paid 100, 20 left
INV-1: rejected, overpayment: 20 outstanding
INV-1: paid 20, 0 left
receipts sent: ['INV-1']

Because Protocol is structural, InMemoryInvoices never says it implements InvoiceRepository. It just has the right methods, and a type checker like mypy confirms it.

The GoF pattern underneath. Every adapter here is a literal Adapter: it makes SQL, SMTP or an in-memory dictionary fit an interface the application chose. Swapping one adapter for another (a real database in production, a fake in tests) is Strategy. The rule tying it together is the dependency inversion principle, the "D" in SOLID.

When not to use it. Clean architecture pays off when the business rules are the valuable, long-lived part. For a CRUD screen that maps a form to a table, it's four projects and three interfaces to save one row. The common failure mode is a repository interface that mirrors the ORM one to one, plus a "service" that only forwards calls to it. If a layer only passes data through, it's cost without benefit. Another warning sign: one interface per class, each with exactly one implementation and no test that uses a fake. Add the port when you have a second implementation or a test that needs one.

Vertical slice architecture

The problem. In a layered codebase, adding one feature means editing a controller, a service, a service interface, a repository, a repository interface, a DTO and a mapper, in seven folders. Each layer is "reusable", but in practice each method is used by exactly one feature. Changes are spread wide, and the shared service classes grow into thousand-line files that every feature edits.

The pattern. Jimmy Bogard's vertical slice architecture turns the folders sideways. Each use case (add a task, complete a task, list open tasks) gets one folder or one file with everything it needs: the request, validation, the handler and its data access. Slices share as little as possible. A simple mediator routes each request to its handler, which also gives you one place for cross-cutting concerns like logging and authorization.

var db = new Db();
var mediator = new Mediator()
    .Register<AddTask.Command, string>(new AddTask.Handler(db))
    .Register<CompleteTask.Command, string>(new CompleteTask.Handler(db))
    .Register<ListOpenTasks.Query, string>(new ListOpenTasks.Handler(db));

Console.WriteLine(mediator.Send<AddTask.Command, string>(new("Write the post")));
Console.WriteLine(mediator.Send<AddTask.Command, string>(new("")));
Console.WriteLine(mediator.Send<AddTask.Command, string>(new("Run every snippet")));
Console.WriteLine(mediator.Send<CompleteTask.Command, string>(new(1)));
Console.WriteLine(mediator.Send<ListOpenTasks.Query, string>(new()));

// ---- Features/AddTask: everything for this use case, in one place ----
static class AddTask
{
    public record Command(string Title);

    public sealed class Handler(Db db) : IHandler<Command, string>
    {
        public string Handle(Command cmd)
        {
            if (string.IsNullOrWhiteSpace(cmd.Title)) return "AddTask: title is required";
            var id = db.Tasks.Count + 1;
            db.Tasks.Add(new TaskRow(id, cmd.Title.Trim(), Done: false));
            return $"AddTask: #{id} created";
        }
    }
}

// ---- Features/CompleteTask ----
static class CompleteTask
{
    public record Command(int Id);

    public sealed class Handler(Db db) : IHandler<Command, string>
    {
        public string Handle(Command cmd)
        {
            var i = db.Tasks.FindIndex(t => t.Id == cmd.Id);
            if (i < 0) return $"CompleteTask: #{cmd.Id} not found";
            db.Tasks[i] = db.Tasks[i] with { Done = true };
            return $"CompleteTask: #{cmd.Id} done";
        }
    }
}

// ---- Features/ListOpenTasks: a read slice can skip the domain model entirely ----
static class ListOpenTasks
{
    public record Query;

    public sealed class Handler(Db db) : IHandler<Query, string>
    {
        public string Handle(Query _) =>
            "Open: " + string.Join(", ", db.Tasks.Where(t => !t.Done).Select(t => $"#{t.Id} {t.Title}"));
    }
}

// ---- Shared plumbing: kept deliberately thin ----
record TaskRow(int Id, string Title, bool Done);
sealed class Db { public List<TaskRow> Tasks { get; } = []; }

interface IHandler<in TRequest, out TResponse> { TResponse Handle(TRequest request); }

sealed class Mediator
{
    private readonly Dictionary<Type, object> _handlers = [];

    public Mediator Register<TRequest, TResponse>(IHandler<TRequest, TResponse> handler)
    {
        _handlers[typeof(TRequest)] = handler;
        return this;
    }

    public TResponse Send<TRequest, TResponse>(TRequest request) =>
        ((IHandler<TRequest, TResponse>)_handlers[typeof(TRequest)]).Handle(request);
}
AddTask: #1 created
AddTask: title is required
AddTask: #2 created
CompleteTask: #1 done
Open: #2 Run every snippet

In ASP.NET Core you often don't need a mediator library at all. A minimal API endpoint per slice, such as app.MapPost("/tasks", (AddTask.Command cmd, Db db) => new AddTask.Handler(db).Handle(cmd)), is already a vertical slice, and endpoint filters cover the cross-cutting part.

The Python version uses a decorator to register handlers, and puts logging in send so every slice gets it for free:

from dataclasses import dataclass, replace
from typing import Callable

# ---- Shared plumbing: a registry and one cross-cutting behaviour ----
HANDLERS: dict[type, Callable] = {}
DB: dict[int, "TaskRow"] = {}


def handles(request_type: type):
    def register(fn):
        HANDLERS[request_type] = fn
        return fn
    return register


def send(request):
    handler = HANDLERS[type(request)]
    result = handler(request)
    print(f"  [log] {type(request).__name__} -> {result!r}")  # one place for logging, auth, timing
    return result


@dataclass(frozen=True)
class TaskRow:
    id: int
    title: str
    done: bool = False


# ---- features/add_task.py ----
@dataclass(frozen=True)
class AddTask:
    title: str


@handles(AddTask)
def add_task(cmd: AddTask) -> str:
    if not cmd.title.strip():
        return "title is required"
    task_id = len(DB) + 1
    DB[task_id] = TaskRow(task_id, cmd.title.strip())
    return f"#{task_id} created"


# ---- features/complete_task.py ----
@dataclass(frozen=True)
class CompleteTask:
    id: int


@handles(CompleteTask)
def complete_task(cmd: CompleteTask) -> str:
    if cmd.id not in DB:
        return f"#{cmd.id} not found"
    DB[cmd.id] = replace(DB[cmd.id], done=True)
    return f"#{cmd.id} done"


# ---- features/list_open_tasks.py ----
@dataclass(frozen=True)
class ListOpenTasks:
    pass


@handles(ListOpenTasks)
def list_open_tasks(_: ListOpenTasks) -> list[str]:
    return [f"#{t.id} {t.title}" for t in DB.values() if not t.done]


send(AddTask("Write the post"))
send(AddTask("   "))
send(AddTask("Run every snippet"))
send(CompleteTask(1))
send(CompleteTask(7))
send(ListOpenTasks())
  [log] AddTask -> '#1 created'
  [log] AddTask -> 'title is required'
  [log] AddTask -> '#2 created'
  [log] CompleteTask -> '#1 done'
  [log] CompleteTask -> '#7 not found'
  [log] ListOpenTasks -> ['#2 Run every snippet']

Notice that the read slice returns plain strings straight from the rows. Slices don't have to share a model. A query can use a hand-written SQL view while a command uses a rich domain object. That freedom is a quiet step toward CQRS, which comes up again in Data at Scale.

The GoF pattern underneath. Each request object is a Command: an action turned into data you can route, log and validate. The dispatcher is a Mediator: slices never call each other, they go through one hub. Both are covered in Command, Chain of Responsibility, Mediator and Template Method. The logging step in send is the start of a Chain of Responsibility, which is what MediatR calls pipeline behaviors.

When not to use it. Slices trade reuse for locality, so they can duplicate logic. If three slices all compute an order total, that rule belongs in a shared domain object, not copied three times. Slices work best when the team is disciplined about pulling real business rules down into the domain and leaving only use-case glue in the slice. They also don't fit well when most of the code is a shared engine with many entry points (a pricing engine, a rules engine), where the engine is the product and features are thin.

How they fit together

These patterns stack. Here's the shape I'd reach for in a growing backend:

src/
  Orders/                     <- module (modular monolith)
    Contracts/                <- the Facade other modules may use
    Features/
      PlaceOrder/             <- vertical slice
      CancelOrder/
    Domain/                   <- shared rules for this module (clean architecture's inner ring)
    Infrastructure/           <- adapters: database, payment gateway
  Inventory/
    ...
  Host/                       <- composition root: wires modules together

Modules give you walls. Slices keep features easy to find. Dependency inversion keeps the rules testable. If the app is small, the folders alone are enough, and you add the boundary checks once the walls start to matter.

The next post, Screen and App Architecture, takes the same ideas to the client: MVVM, unidirectional data flow and offline-first. Later in the series, How Services Talk covers what changes when a module boundary becomes a network boundary.

Check yourself: questions and answers

1. What's the difference between a modular monolith and microservices?

Both split the system into parts that own their data and expose contracts. A modular monolith deploys them as one process, so calls between modules are method calls: fast, transactional when needed, and easy to debug. Microservices put a network between them, which buys independent deployment and scaling at the cost of latency, partial failure and distributed data. A good modular monolith is the cheapest way to find out where those service boundaries should be.

2. In clean architecture, where does the repository interface live, and why?

In the application or domain layer, next to the code that uses it. The inner ring defines what it needs, and the infrastructure layer implements it. If the interface lived in the data access project, the business logic would depend on the data layer, which is exactly the dependency clean architecture exists to reverse.

3. How do you stop a module boundary from eroding over time?

Make it fail the build. In .NET, use separate projects with internal types, plus architecture tests (NetArchTest, ArchUnitNET, or a reflection check like the one above). In Python, use an underscore convention and a CI check such as Import Linter. A boundary that only lives in a wiki page won't survive the first deadline.

4. Is vertical slice architecture the opposite of clean architecture?

No. They answer different questions. Vertical slices decide how to group code (by feature, not by layer). Clean architecture decides which way dependencies point. A slice that contains real business logic can still keep that logic in domain objects that don't depend on the database. What vertical slices reject is the habit of forcing every feature through the same stack of layers whether it needs them or not.

5. When is a plain layered (N-tier) structure good enough?

When the app is mostly CRUD, the team is small, and the database isn't likely to change. Its known weakness is that business logic depends on data access, which makes testing harder. If you find yourself needing a real database to test a business rule, that's the signal to invert that dependency.

6. What's the composition root?

The one place, usually at startup, where concrete types are created and wired to the interfaces that need them. In ASP.NET Core it's Program.cs and the DI container setup. Keeping all the wiring there is what lets the rest of the code depend only on abstractions.

Further reading

  • Martin Fowler, Monolith First and Microservice Premium
  • Shopify Engineering, Deconstructing the Monolith: Designing Software that Maximizes Developer Productivity
  • Microsoft Learn, Common web application architectures (N-layer versus clean architecture, and the composition root)
  • Azure Architecture Center, Architecture styles
  • Robert C. Martin, The Clean Architecture
  • Alistair Cockburn, Hexagonal Architecture (Ports and Adapters)
  • Martin Fowler, Presentation Domain Data Layering
  • Jimmy Bogard, Vertical Slice Architecture
  • Import Linter for enforcing module boundaries in Python
  • From this blog: The Pattern Map, Design Patterns I Keep Coming Back To
← Previous

Two Azure Outages, and Why Known Problems Still Get Through

Next →

Claude Opus 5.5 Is a Pricing Story About Agents

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.