Skip to content
matthewcm.dev

    ↑ ↓ move · ↵ open · tab scopeopen graph →

    Architecture Fitness Functions

    Automated checks that fail the build when the architecture drifts, like a service importing a database driver directly. Cheap feedback that keeps a codebase on the shape it was designed for.

    Seedtended planted 2 min read

    🌱 A rough idea, planted recently. Expect rough edges — it will grow.

    On this page

    A fitness function is a test of an architectural property rather than a behaviour: coupling, layering, which modules may depend on which. When the architecture drifts, the build fails, instead of the drift quietly piling up.

    A one-file example

    The rule: the service layer talks to repositories, never to the datastore directly. The simplest version just looks for forbidden imports in each layer:

    # test_architecture.py: services never import datastores directly
    from pathlib import Path
    
    FORBIDDEN_IN_SERVICES = ["sqlalchemy", "pymongo", "boto3", "psycopg2"]
    
    def test_service_layer_isolation():
        for service_file in Path("src/services").glob("*.py"):
            source = service_file.read_text()
            for forbidden in FORBIDDEN_IN_SERVICES:
                assert forbidden not in source, f"{service_file.name} imports '{forbidden}' directly"

    It’s crude (a string match, not a dependency graph), but it runs in milliseconds and it catches the mistake on the pull request where it happens. Grown-up versions exist for most ecosystems: ArchUnit for Java, dependency-cruiser for JavaScript and TypeScript, import-linter for Python.

    Worked example: a low-code workflow platform

    What I’d add to a low-code network automation platform I led (Building a Low-Code BPMN Workflow Platform) if I built it again. Each one is an architectural rule turned into a CI check:

    1. Front-end modules stay independent. Feature modules (editor, process instances, workbench) import each other only through a public index.ts, and call the backend only through the shared API client.
    // .dependency-cruiser.js
    module.exports = { forbidden: [
      { name: "no-cross-module-internals",
        from: { path: "^src/modules/([^/]+)/" },
        to:   { path: "^src/modules/(?!$1)[^/]+/(?!index\\.ts$)" } },
      { name: "api-only-through-client",
        from: { path: "^src/modules/" }, to: { path: "node_modules/axios" } },
    ]};
    1. The OpenAPI spec stays the contract. Diff the spec against main with a breaking-change checker (e.g. oasdiff) and run a contract test (e.g. Schemathesis) against the API.
    2. No endpoint without a permission (security lives on the server):
    def test_every_operation_declares_a_permission():
        spec = yaml.safe_load(open("openapi.yaml"))
        for path, ops in spec["paths"].items():
            for method, op in ops.items():
                assert op.get("x-permission"), f"{method.upper()} {path} has no x-permission"
    1. The Jinja gear shift stays safe. Every template renders with sample data (no undefined variables), uses only the sandbox, has no secrets, and produces valid device config:
    env = SandboxedEnvironment(undefined=StrictUndefined)
    schema = etree.XMLSchema(etree.parse("schemas/device-config.xsd"))
    
    def test_every_template_renders_valid_config():
        for tpl in pathlib.Path("templates").glob("*.xml.j2"):
            sample = yaml.safe_load(open(tpl.with_suffix("").with_suffix(".sample.yaml")))
            xml = env.from_string(tpl.read_text()).render(**sample)
            assert "password" not in xml.lower(), f"{tpl.name}: secret in template"
            assert schema.validate(etree.fromstring(xml)), f"{tpl.name}: invalid device config"
    1. Workflows follow the golden path. A custom bpmnlint rule: every workflow has documentation (the lesson from a new user group struggling), and every service task uses a catalogue building block.
    module.exports = () => ({ check(node, reporter) {
      if (node.$type === "bpmn:Process" && !node.documentation?.length)
        reporter.report(node.id, "Workflow needs documentation");
      if (node.$type === "bpmn:ServiceTask" && !node.get("platform:blockId"))
        reporter.report(node.id, "Service task must use a catalogue building block");
    }});
    1. Operational rules: every SSE endpoint sends heartbeats and has a timeout; the front end has a bundle-size budget.

    The point: the most valuable check guards the escape hatch. Engineers can go deep with Jinja templates, but they can’t drift outside the rules.

    Why bother

    Drift is the default. Plenty of projects start with a clean, well-layered architecture and slowly lose it under delivery pressure. That’s understandable: deadlines are real. A fitness function doesn’t stop you shipping; it makes the shortcut visible and pulls you back on track without a big-bang rewrite.

    They also keep the people side honest. If the layers map to teams (product teams on top, platform teams underneath, as in The Platform Relevance Gap), enforcing the boundaries in code keeps each team working at the right layer.

    Run them in CI next to everything else: they’re the architectural end of Shift Left Testing.

    Through a training lens

    It’s like seeing a physio when something starts to feel off, or asking a coach to check your technique. You can usually coach yourself through a programme, but outside feedback, or simply filming your sets, gives you the small corrections that keep you progressing instead of slowly grooving a bad pattern. A fitness function is that video, recorded on every commit.

    From chapter 3 of Domain-Driven Platform Engineering.

    • #architecture
    • #fitness-functions
    • #ci
    • #coupling
    • #domain-driven-design

    ↪ Links to (3)