Architecture Fitness Functions: Testing Architecture Over Time
Architecture fitness functions are automated tests for your system's structural properties. Here's how to implement the 5 most impactful ones and integrate them into your CI pipeline.
We had a beautiful microservices architecture. Clean service boundaries. Well-defined APIs. Proper event-driven communication. It took us 9 months to build. Within 18 months, it had degraded into a distributed monolith where 7 services were so tightly coupled that deploying one required testing all 7. Nobody made a conscious decision to couple them. It happened one PR at a time, each change perfectly reasonable in isolation, collectively destructive.
This is the problem that architecture fitness functions solve. They're automated tests for your architectural properties, and they catch drift before it becomes rot. I've been implementing them for 3 years across 4 codebases, and they've changed how I think about architecture entirely.
# What Architecture Fitness Functions Actually Are
The concept comes from Neal Ford, Rebecca Parsons and Patrick Kua's work on evolutionary architecture, set out in their book Building Evolutionary Architectures. The idea is simple: if you can write unit tests for code behavior, you can write tests for architectural properties.[1]
A fitness function is any automated check that validates an architectural property you care about. It runs in CI just like your unit tests. When it fails, it means your architecture has drifted from its intended design.[2]
Examples of what fitness functions test:
Service dependency direction (Service A can depend on Service B, but not the reverse)
Maximum allowed latency for critical paths
Database query patterns (no N+1 queries in specific services)
Module boundaries (the billing module can't import from the user interface module)
Maximum dependency depth (no more than 3 hops between any two services for a user-facing request)
These aren't performance tests or integration tests. They're structural assertions about how your system is organized.
Here's the contrarian take: code review is terrible at catching architectural drift. I analyzed 2,400 PRs across two codebases over a 12-month period. In that time, 34 PRs introduced architectural violations (wrong dependency directions, new coupling between services that shouldn't communicate, etc.). Code reviewers caught 6 of them. That's an 18% detection rate.
The reason is human: reviewers are focused on the code in front of them. They're checking logic, error handling, naming, and test coverage. They're not mentally simulating the dependency graph to verify that this new import doesn't create a circular dependency three hops away. That's an unreasonable expectation for a human reviewer, and it's a perfect job for an automated check.
I'll walk through the 5 fitness functions I implement first on any codebase. These cover the most common architectural drift patterns I've seen.
# Fitness Function 1: Dependency Direction Enforcement
This ensures that dependencies flow in the correct direction (typically from higher-level modules toward lower-level modules, never the reverse).[3]
Figure 1. Allowed imports point down the layers. A reverse import, such as models reaching back into services, fails the test before it can merge.
typescript
// fitness/dependency-direction.test.tsimport { getImports } from "./utils/ast-parser";import * as glob from "glob";const DEPENDENCY_RULES = { "src/api/**": { canImportFrom: ["src/services/**", "src/models/**", "src/utils/**"], cannotImportFrom: ["src/infrastructure/**", "src/jobs/**"], }, "src/services/**": { canImportFrom: ["src/models/**", "src/utils/**", "src/repositories/**"], cannotImportFrom: ["src/api/**", "src/jobs/**"], }, "src/models/**": { canImportFrom: ["src/utils/**"], cannotImportFrom: ["src/api/**", "src/services/**", "src/repositories/**"], },};describe("Dependency Direction", () => { for (const [modulePattern, rules] of Object.entries(DEPENDENCY_RULES)) { const files = glob.sync(modulePattern); for (const file of files) { test(`${file} respects dependency direction`, () => { const imports = getImports(file); for (const imp of imports) { for (const forbidden of rules.cannotImportFrom) { expect(imp).not.toMatch(new RegExp(forbidden.replace("**", ".*"))); } } }); } }});
We caught 12 violations in the first month after adding this. Twelve cases where a model was importing from a service, or an API handler was directly accessing the database layer. Each one was a small crack that would've become a structural problem.
# Fitness Function 2: Service Communication Boundaries
For microservices or modular monoliths, this validates which services can communicate with which.
Fitness functions should run on every PR, just like unit tests. I split them into two categories:
Fast fitness functions (run on every PR): Dependency direction, service boundaries, database access patterns, component size. These are static analysis checks that complete in seconds.
Slow fitness functions (run nightly): Latency budgets, load test thresholds, cross-service integration properties. These require runtime data or take longer to execute.[4]
Figure 2. Split by speed: static checks gate every merge, runtime checks run nightly and report drift.
# The Stealable Framework: Fitness Function Adoption in 4 Sprints
Sprint 1: Audit and Define
Document your intended architecture (what should depend on what, which services communicate, etc.)
Identify the top 3 architectural properties you care about most
Write fitness functions for dependency direction only
Sprint 2: Expand Coverage
Add service boundary and database access fitness functions
Run against the current codebase and fix existing violations (there will be many)
Establish baseline metrics
Sprint 3: Runtime Properties
Add latency budget and component size fitness functions
Integrate into CI pipeline
Create a dashboard showing fitness function trends over time
Sprint 4: Team Adoption
Every new RFC must include which fitness functions the proposed change might affect
Add fitness function creation to the "definition of done" for new modules/services
Review fitness function coverage quarterly
After 3 months on this cadence, architecture drift went from "something we noticed in quarterly reviews" to "something CI catches in 10 minutes." Our architecture violation rate dropped from 34 violations per year to 3. Not because engineers stopped making mistakes, but because they got feedback within minutes instead of months.
Your architecture is either being tested or it's being eroded. There's no middle ground. Fitness functions put architecture on the same footing as code correctness: if it matters, it has a test.
MachGTM, which I build, provides a sales-workflow example of an invariant worth testing near execution. The inspected path compares selected stored inputs before a waiting task or send proceeds, while recorded replies and contact stops have separate checks. The engineering account explains the changed-fact check and its review-policy limits. Use the example to specify the changed input, expected move state and policy applied when the work is planned again.
Frequently asked questions
How are fitness functions different from unit tests?
Unit tests check behaviour: given this input, expect that output. Fitness functions check structure: which modules may depend on which, how large a component may grow, how long a critical path may take. They run in the same pipeline, but they fail when the shape of the system drifts, even while every feature still works.
Do I need a dedicated tool to write them?
No. The examples here are plain test files that parse imports and assert rules. For JavaScript and TypeScript, dependency-cruiser checks import rules you define, which saves writing the parser yourself.
Which fitness functions should block a pull request?
The static ones: dependency direction, service boundaries, database access patterns and component size. They finish in seconds. Latency budgets and load thresholds need runtime data, so run them on a schedule and report drift instead of blocking merges.
What if the existing code already breaks the rules?
Record today's violations as a baseline and fail the build only on new ones. Then shrink the baseline deliberately. Turning a rule on with dozens of existing failures teaches the team to ignore it.
Five predictions for where code intelligence is heading by 2028, based on 6 years of building tools in this space. Includes what's real, what's overhyped, and a maturity model for planning.
Most code quality dashboards fail because they track too many metrics and live outside the team's workflow. Here are exactly 7 metrics and a 3-week adoption plan that actually works.
Build software composition analysis into CI with dependency inventories, vulnerability checks and licence review. Define owners, response targets and follow-up.
Your PR data reveals team bottlenecks invisible in standups. Here's how to measure TTFR, review distribution, and cycle time with the REVIEW framework.