My account

Fitness Functions and Architecture Governance

A rule that lives only in a document is slowly broken. A fitness function turns an architecture goal into an automatic check: a test that reads the code, a load test with a limit, or an alert in production. When a check fails, the pipeline stops, and an exception needs a reason and an end date.

Not reviewedWritten with AI helpReading time: 12 minOnline shop exampleC# architecture testLoad test limits

Author: bezzad

Contents

The problem: the design and the code slowly separate

A year ago our online shop team agreed on two rules and wrote them in ADRs:

  1. The API layer never talks to the database code (the Infrastructure layer) directly. It goes through the application services.
  2. 95% of checkouts finish in under 300 ms at lunch time.

Today a review finds 40 places where the API uses the database code. And checkout takes 900 ms. Nobody broke the rules on purpose. Each change was small, and each time someone was in a hurry.

This slow movement away from the design is called architecture drift (or erosion). Every team has it. The question is only whether you see it early or late.

Months after the design was agreed036912closefarThe agreed designNo checks: slow driftWith fitness functionsa check fails, the team fixes it
Without checks, the code drifts a little every month. With checks, a failure shows up quickly and is fixed while it is small.

The idea: a test for the architecture

A fitness function is any automatic check that tells you how close the system is to one architecture goal. The name comes from evolution: it measures how “fit” the system still is.

You already know some of them. A unit test checks a feature. A fitness function checks a characteristic: structure, speed, security, availability.

There are two main kinds:

Kind What it does When it runs Example
Static Reads the code or its settings At build time “No class in the API layer uses the Infrastructure layer”
Dynamic Runs the system and measures it Before release, or all the time in production “95% of checkouts under 300 ms at 5,000 a minute”

A dynamic check that runs all the time in production is a continuous check. Monitoring alerts and SLOs are fitness functions too.

Where the checks run

CommitBuild and unit testsArchitecture testsDeploy to test serversLoad testProduction monitorsStatic: reads the codeAPI must not use Infrastructure. No module cycles.Dynamic: runs the system95% of checkouts under 300 ms at 5,000 a minute.Continuous: watches real usersAlert if errors stay above 0.1% for 5 minutes.If a check fails, the pipeline stops.The rule is a test, not a wiki page.
Each check runs where it is cheapest and still trustworthy. A failed check stops the line.
  1. At build time. Architecture tests read the compiled code. They are fast and cheap, so run them on every commit.
  2. Before release. A short load test on a test server checks the speed numbers. It is slower, so run it before each release or each night.
  3. In production. Monitors watch real users. They catch what tests miss, like a slow third-party service.

Example 1: a static check for the layer rule

In .NET, a library like NetArchTest (or ArchUnitNET) lets you write the rule as a normal unit test:

using NetArchTest.Rules;
using Xunit;

public class ArchitectureTests
{
    [Fact]
    public void Api_does_not_use_infrastructure()
    {
        var result = Types.InAssembly(typeof(OrdersController).Assembly)
            .That().ResideInNamespace("Shop.Api")
            .ShouldNot().HaveDependencyOn("Shop.Infrastructure")
            .GetResult();

        Assert.True(result.IsSuccessful,
            "Broken by: " + string.Join(", ", result.FailingTypeNames ?? []));
    }
}

A few points:

  • The test lives next to the other tests. So it runs in the same pipeline with no extra work.
  • The failure message names the classes that break the rule. The developer sees it in seconds, not in a review a year later.
  • Other useful structure rules: no cycles between modules, one module uses another only through its contract, domain classes do not use the web framework.

Example 2: a dynamic check for the speed rule

A load test tool like k6 can fail the run when a number is too high. This script sends 5,000 checkouts a minute for 10 minutes:

import http from 'k6/http';

export const options = {
  scenarios: {
    lunchPeak: {
      executor: 'constant-arrival-rate',
      rate: 5000, timeUnit: '1m', duration: '10m',
      preAllocatedVUs: 200,
    },
  },
  thresholds: {
    'http_req_duration{name:checkout}': ['p(95)<300'],
    http_req_failed: ['rate<0.001'],
  },
};

export default function () {
  const body = JSON.stringify({ cartId: 'demo-cart' });
  http.post(`${__ENV.BASE_URL}/checkout`, body, {
    headers: { 'Content-Type': 'application/json' },
    tags: { name: 'checkout' },
  });
}

If 95% of checkouts are not under 300 ms, or more than 0.1% fail, k6 ends with an error code. The pipeline sees the error and stops the release.

Notice that the numbers are the same numbers as the quality scenario. A good fitness function is a scenario written as code.

Governance: rules people can live with

“Governance” sounds heavy. Here it means only: how the team keeps the architecture rules true over time. A few simple habits:

  1. Fail the build. A rule that only creates a warning is ignored after a month.
  2. Start small. Pick the two or three rules that hurt most when broken. Add more later.
  3. Allow exceptions, but write them down. Sometimes breaking a rule is the right short-term choice. Then add an entry with the reason, the owner and an end date. When the date comes, fix it or decide again.
  4. Watch the trend, not only pass or fail. For example, the number of exceptions, the number of cycles, or the p95 time per month. A slow rise is an early warning.
  5. Link each check to its ADR. The ADR says why the rule exists. The check says whether it is still true. If the reason changes, change both.
A sign of good governance: New team members learn the rules from failing tests, not from a long document. The tests are the living version of the architecture.

Which characteristic, which check?

Characteristic A fitness function
Modifiability No cycles between modules; each module is used only through its contract
Performance p95 time under a limit in a load test
Availability Monthly uptime from monitoring; a test that kills one server and checks that orders still work
Security Dependency scan with no known high-risk library; no secrets in the repository
Deployability A release from commit to production in under one hour
Testability Unit tests run in under five minutes

Common mistakes

Mistake Result The right way
Rules only in a wiki or ADR Drift that nobody sees for months. One automatic check per important rule.
Checks that only warn Warnings pile up and are ignored. Fail the build or the release.
Fifty rules on day one Slow pipeline, angry team, rules get disabled. Start with two or three rules.
Exceptions with no end date The exception becomes the new rule. Reason, owner and end date for each one.
Only static checks Fast code structure, slow real system. Add load tests and production alerts.

Summary in six lines

  1. Code slowly drifts from the agreed design; this is normal and must be watched.
  2. A fitness function is an automatic check for an architecture characteristic.
  3. Static checks read the code at build time; dynamic checks run the system and measure it.
  4. Production monitors and SLO alerts are continuous fitness functions.
  5. Fail the build, start small, and give every exception a reason and an end date.
  6. A good fitness function is a quality scenario written as code, linked to its ADR.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.