David Zurillo

A local stack that fails like production: the Knowby developer environment

How I set up local development for Knowby's web, mobile and .NET backend: one compose file, three replicas behind a load balancer, a fault proxy, a seeder, test shards and tests at every layer.

Most local development environments are built to make things work. Mine for the Knowby platform is built to make things fail, in the same ways production fails, before they get there.

Knowby is one monorepo. It holds a .NET 10 backend of seven API servers and background jobs on PostgreSQL, a React web app, native SwiftUI iOS and Kotlin Android apps, a Chrome extension and a few smaller tools. In production the servers run on Google Cloud Run, several instances each, with self-hosted AI on NVIDIA GPUs. Locally, the whole platform comes up from one Docker Compose file.

This post walks through that environment end to end:

  • the compose stack and the database tuned to throw data away quickly
  • the same Docker images built for development and released to production through Cloud Build and Cloud Run
  • the load balancer that mirrors production's, so one local stack behaves like many instances
  • the seeder that puts every test in a known state
  • the fault proxy that breaks real traffic on purpose
  • test shards that run thousands of tests in under a minute
  • the test layers and guards that keep it all honest

It's long and specific on purpose. Most of the decisions came from a failure, and the failure is usually the interesting part.

Why build all this

Knowby is used every day by people on a phone or tablet out in a factory, a depot or a farm, where the connection isn't always good. When something goes wrong for them, it's less likely to be a crash on a dashboard and more likely to be a guide that didn't sync, a change that reached one screen but not another, or an app that spun forever on a captive Wi-Fi network.

Those are the hardest bugs in the platform, and they have something in common: they come from the gaps between parts, not from inside any one of them.

  • Several instances. Production runs several copies of every server, and a request can land on any of them. A cache one instance forgot to clear is invisible when only one copy is running.
  • Imperfect networks. Phones go offline, connections hang, streams drop halfway, tokens expire mid-request. A local network never does any of that on its own.
  • Real data over time. Schedules depend on today's date, records pile up, and caches fill. Hand-made test data is small, static and kind.
  • Real side effects. Email, push notifications and background jobs reach real people and real GPUs.

A typical local setup has one copy of each server, a perfect network and a handful of hand-made records. It's built to make the happy path work, so these bugs survive it and turn up in production, where they're slowest and most expensive to diagnose.

I'd also tried the usual workaround, faking the network inside the app, and seen it fail. A fake API is a second copy of the server's behaviour, maintained by hand. It drifts, and when it does, the fake and the app agree with each other while both are wrong. The tests pass and the bug ships.

Then there's speed. When a reset takes half a second and a suite takes 25 minutes per device, people stop running the tests, and a test nobody runs proves nothing. For a small team, and for AI coding agents that write a lot of code quickly, the checks have to be fast and trustworthy enough to run on every change.

So the goal became one sentence: any failure production can produce, I should be able to produce locally, on demand, in seconds, the same way every time. Everything below serves that goal.

One compose file, the whole platform

Diagram: iOS simulators, Android emulators and browsers call the servers through a fault proxy in end-to-end tests, or straight to the load balancer day to day. An nginx load balancer round-robins across three replicas of each of seven servers, which share one PostgreSQL 17 on a RAM disk. A one-shot seeder and a Docker API proxy sit alongside

The compose file defines 13 services:

  • PostgreSQL 17, holding one database per service: identity, pro, public web, media proxy and jobs.
  • Seven API servers: Identity, Pro, Translation, Media Proxy, Jobs, Intelligence and Public Web. Each runs as three replicas.
  • The Pro web app, a single container serving static files on port 8081.
  • An nginx load balancer that owns every server port on the host.
  • The fault proxy, a small Python service that sits between the apps and the servers in end-to-end tests.
  • The seeder, a one-shot container that resets every database to a known state.
  • A Docker API proxy, so that simulators, emulators and browsers can start the seeder.

A full up gives 21 API server containers, plus Postgres, the web app, the load balancer, the fault proxy and the Docker API proxy.

Everything builds from source. There's no pre-built image to pull. That costs some build time, but every developer runs exactly the code in their checkout. The service Dockerfiles are multi-stage and copy files in two phases: first the project files and a restore, then only the source that service compiles. An edit to another server or to a client then doesn't invalidate the image's build layers.

The containers run a Release build, not a Debug one, because that's what production runs. That choice matters later, when I need behaviour that exists only locally: I can't use #if DEBUG for it.

A database built to be thrown away

Local data is disposable, so Postgres is tuned for speed rather than durability:

knowby-postgres-server:
  image: postgres:17.5-alpine
  tmpfs:
    - /var/lib/postgresql/data:size=8G
  command: ["postgres", "-c", "max_connections=1000", "-c", "fsync=off",
            "-c", "synchronous_commit=off", "-c", "full_page_writes=off",
            "-c", "wal_level=minimal", "-c", "max_wal_size=256MB"]

The data directory is a RAM disk, with fsync, full-page writes and synchronous commits all off. Nothing survives a restart, and nothing needs to: the seeder rebuilds it all.

The RAM disk's size is set by measurement, and two failures shaped it:

  • The disk filled up. Each test shard (more on those below) holds a private copy of every database, roughly 90 to 100 MB. Twenty-four shards on a 2 GB disk failed 1,174 of 1,459 tests, every one with "No space left on device". So the disk is 8 GB, and the shard runner now measures the free space on the volume before it creates any shards.
  • The write-ahead log outgrew the disk. max_wal_size was once 2 GB on a 1 GB RAM disk. That showed up as intermittent, wandering test failures, which I misread first as a race when dropping databases and then as a reconnection storm. The setting now stays well under the disk size, with a comment in the compose file saying why.

One side effect to know about: recreating the Postgres container empties every database. When I rebuild servers, I pass --no-deps so Compose doesn't recreate Postgres along with them.

The same containers in development and production

The local stack isn't a lookalike of production. It's built from the same files that production is built from.

Every API server has one Dockerfile, and that one file is used everywhere:

  • Locally, Docker Compose builds each server from its Dockerfile.
  • Into production, Cloud Build builds the same Dockerfile from the same commit, pushes the image to Artifact Registry and deploys it to Cloud Run.
  • In GitHub Actions, a workflow builds the same Dockerfiles again when code reaches the UAT branch and scans every image for vulnerabilities before it's released.

So the image running locally and the image serving customers share:

  • the same .NET base images, pinned to the same versions
  • the same Release build
  • the same multi-stage steps and final stage
  • the same non-root user, port and time zone

A dependency upgrade, a base-image patch or a change to the build reaches local development and production through the same line of the same file. It can't be tested on one and differ on the other.

The background jobs follow the same pattern. Each Cloud Run job has its own Dockerfile, and one shared Cloud Build configuration builds and deploys any of them. It's a two-step pipeline:

  1. Build: BuildKit builds the image with a registry cache. The CUDA base, the model downloads and the llama.cpp compile take most of a cold build and rarely change, so they're reused rather than rebuilt. The image is pushed from the build step itself, so it exists before the deploy step asks for it.
  2. Deploy: gcloud run jobs deploy points the job at the new image.

Each environment has its own trigger, tied to its own branch: development, UAT and production. All three are run deliberately, never on every push, so a release is always a decision someone made.

The differences between local and production are few, deliberate and written down:

  • Configuration: the environment name is Local instead of a deployed one, and settings come from a local environment file instead of the deployed configuration. That's what switches on local-only behaviour, such as running jobs in-process and the email kill switch, and a deployed process can't take those paths.
  • Hardware: the jobs server has two local Dockerfile variants, one with CUDA and one without, because a development machine's GPU isn't production's.
  • Load balancing and instance count: nginx stands in for the production load balancer, and three replicas of each server stand in for Cloud Run's many autoscaled instances.
  • Resource limits: environment settings cap cache memory and turn off server garbage collection, so the containers behave like small production instances.

Everything else is the same. When a bug appears locally, it's a bug in what ships, not in a separate development build.

Three of everything: the load balancer

In production, a Google Cloud load balancer sits in front of every Cloud Run service, and Cloud Run runs many instances of each server, scaling them up and down with demand. A client's consecutive requests can land on different instances. Anything that only holds on one instance is a bug waiting to happen. An in-memory cache nothing evicts is one example; a token only one instance has heard about is another. Such bugs never show up in a local setup running one copy of each server.

So locally, the shape is the same: a load balancer in front, several instances behind it. Every server runs three replicas behind nginx, round-robin per request:

http {
    resolver 127.0.0.11 valid=5s ipv6=off;
    proxy_buffering off;
    proxy_read_timeout 3600s;
    proxy_set_header Host $http_host;
    add_header X-Knowby-Instance $upstream_addr always;

    upstream identity { zone identity 64k; server knowby-identity-api-server:8080 resolve; }
    upstream pro      { zone pro 64k;      server knowby-pro-api-server:8080 resolve; }

    server { listen 3000; location / { proxy_pass http://identity; } }
    server { listen 3001; location / { proxy_pass http://pro; } }
}

(Abridged: the real file has every server and a few more proxy settings.)

This matters because Knowby has no Redis. Each server instance caches in memory and evicts entries when PostgreSQL sends a change notification. With three instances locally, a missed eviction fails locally, not first in production.

A few details carry their weight:

  • Upstreams resolve through Docker's DNS. nginx finds the replicas by service name and re-resolves every few seconds, so a restarted replica rejoins without restarting nginx.
  • Every response names its instance. The X-Knowby-Instance header records which replica answered. Tests use it to prove that every instance has seen a reseed before a test starts.
  • Streams stay open. Knowby pushes changes to clients over Server-Sent Events that stay open for up to 55 minutes, with a heartbeat every 15 seconds. Buffering is off and the read timeout is an hour.
  • The Host header passes through. The servers build URLs from the request, for example SCIM base URLs and OAuth issuers, so they need to see the host the client used.

The Pro web app is the one exception: one instance on port 8081, outside the load balancer. It serves static files and keeps no state. Port 8081 is also the origin Firebase sign-in is authorised for, so when I run Vite's dev server for the web app, it takes the same port.

Making containers behave like a small production instance

Two environment settings make the containers behave like their production counterparts, and both came from surprises.

The first is DOTNET_gcServer=0 on every .NET service. Server garbage collection allocates one heap and one thread per visible core, and Docker Desktop hands every container every core on the host. With dozens of .NET processes running at once, that adds up fast: one run produced 1,172 ".NET Server GC" threads across roughly 135 processes, starved the operating system for 93 seconds and triggered a kernel watchdog panic. Turning server GC off on every service fixed it.

The second is an explicit cache memory limit of 512 MiB on the servers that cache heavily. Without it, a process asks how much memory the machine has, sees far more than any production instance gets, and sizes its cache to match. The cache's bound is then never reached and the eviction code never runs. 512 MiB is a small Cloud Run instance, so the eviction path gets exercised locally just as it would in production.

GPUs, and the jobs server on the host

The jobs server runs the AI work: Whisper transcription, OCR, a vision-language model and FFmpeg. That makes it the one service whose environment depends on the hardware.

There are two compose files, identical except for one line: the jobs server's Dockerfile.

  • On an NVIDIA machine, the image installs CUDA 13 and cuDNN and downloads the models. It also compiles llama.cpp's server with CUDA in a separate build stage. The vision model is a 4-bit quantised build, because a local GPU has less memory than the one production uses. The compile job count is capped, because an unbounded parallel build once ran Docker Desktop's virtual machine out of memory.
  • Everywhere else, transcription and OCR run on the CPU and the vision model is left out. A 9-billion-parameter model on a CPU is too slow to be useful. Without it, the job still cuts a video into steps at scene changes, just without step text.

On Apple silicon there's no GPU passthrough in Docker, so jobs that transcribe or transcode crawl inside a container. The rule is to run the jobs server on the host instead, where it can use a Mac's GPU and hardware encoders. The load balancer makes that a drop-in swap:

upstream jobs {
    zone jobs 64k;
    server knowby-jobs-api-server:8080 resolve;
    server host.docker.internal:3016 backup resolve;
}

Scale the jobs containers to zero and nginx sends jobs traffic to the copy running on the host on port 3016. Nothing else changes:

docker compose -f docker-compose-local-no-cuda.yml up -d --scale knowby-jobs-api-server=0
dotnet run --project knowby-servers/Jobs/Knowby.Jobs.Server

In production, a job is dispatched to a Cloud Run job. Locally, the server runs it in-process, so the whole pipeline can be stepped through in a debugger.

Connecting mobile and web to the stack

Locally, everything is plain HTTP on localhost; the deployed environments are HTTPS only. Each client needs a slightly different trick to reach it.

iOS. The DEV build configuration names just one server: Identity, on http://localhost:3000. (In an .xcconfig file, // starts a comment, so it's spelled http:/$()/localhost:3000.) The app learns every other service's URL from the organisation record it signs into, the same way it does in production. Simulators share the Mac's network, so localhost works directly. The DEV, TEST and PROD builds have distinct bundle IDs, so all three can sit side by side on one device. DEV builds report nothing to crash reporting or analytics.

A DEV build on a physical iPhone can't use localhost, because there it means the phone. Debug-only environment overrides point it at the Mac instead; a Release build ignores them.

Android. An emulator doesn't share the host's loopback. Instead of the usual 10.0.2.2 alias, each emulator gets an adb reverse for every port it uses. The app's localhost URLs, the service URLs stored in the database, and Firebase's authorised origin then all work unchanged. Cleartext HTTP is allowed only in the dev build flavour, and only to the loopback addresses:

<network-security-config>
    <base-config cleartextTrafficPermitted="false" />
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="false">localhost</domain>
        <domain includeSubdomains="false">127.0.0.1</domain>
    </domain-config>
</network-security-config>

Web. Vite serves the web app on port 8081, the origin Firebase allows. A local-only build can point the app at the fault proxy or at a test shard through a localStorage override. Deployed builds compile that override away.

Windows. A small PowerShell script forwards ports from a Windows virtual machine's localhost to the Mac, so a browser in the VM can use the same stack.

Sign-in. Authentication is real Firebase, using a development project, in every test layer above unit tests. Nothing about sign-in is faked once the app talks to a server.

Seed data you can trust

Every test, on every platform, starts from the same known data. That data comes from a seeder, and the seeder has a few rules.

It seeds through the real code. The seeder starts each server in-process (Identity, Media Proxy, Jobs, Pro and Public, in that order) and creates data through the servers' own services and repositories. It never writes SQL by hand. If the servers' rules change, the seed changes with them, and seed data can never be something the app itself couldn't have created.

It's deterministic. A fixed clock sets "now" to 15 January 2026 at 10:00 UTC. The "random" generator returns the midpoint of any range. Stable records have hard-coded IDs. Two runs produce byte-identical output.

Its output is committed. --dump seeds and writes five SQL dumps into the repository; --restore loads them. The rule for changing seed data is to change the seeder, regenerate every dump, check that it reports zero errors, and review the seeder code, never a diff of the dumps.

Any error fails the run. A seeding run with even one error exits with a failure. That rule exists because a Media Proxy regression once failed 187 of 217 inserts and nobody noticed.

Dates follow the calendar. The dumps are frozen at 15 January, but a client asking for "today's" schedules needs to find some. So after every restore, a date shift moves the seeded schedules from the seed day to the real today, in Sydney time and by whole days, so that weekday rules still hold.

Resetting in 45 milliseconds

xUnit creates a new instance of a test class for every test method, so a reset in the constructor runs once per test. The Pro suite alone resets 678 times. Replaying the SQL dumps took roughly 300 to 560 ms each time, which added up fast.

So the dump is loaded once into a knowby_pristine schema alongside the live public schema. A reset becomes TRUNCATE followed by INSERT … SELECT, entirely inside the database server. That takes about 45 ms for Pro and Identity together. A few details make it safe:

  • The copy runs with session_replication_role = 'replica', so the trigger that stamps every row's entity tag doesn't rewrite the tags. A reset row is byte-identical to the seeded one.
  • Sequences are restored too.
  • A signature of the schema's shape is checked on every reset. If the schema or the dump file changed, it falls back to a full replay.
  • The schema is never dropped, so the servers keep their warm connection pools across resets.

A guard test changes data in every database and then asserts that a restore puts it back byte for byte.

Reseeding from a simulator

Diagram: a reseed before every test. The test starts the seeder through the Docker API; the seeder restores from a pristine schema in about 45 milliseconds; seeded dates shift to today; the harness waits until every server instance has heard the reseed; then the test runs

A UI test on a simulator, an emulator or in a browser has to reset the database before it starts. It can't run docker commands, and it can't reach the host's Docker socket. So a tiny sidecar exposes the Docker Engine API on the loopback address only:

docker-api-proxy:
  image: alpine/socat
  command: TCP-LISTEN:2375,fork,reuseaddr UNIX-CONNECT:/var/run/docker.sock
  ports:
    - "127.0.0.1:2375:2375"
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock

An unauthenticated Docker API amounts to root access to the machine, which is why it's bound to 127.0.0.1 and nothing else, and why the servers never use it. A reseed is then two REST calls from any test harness. This is the Playwright version:

const start = await post(`/containers/${SEEDER_CONTAINER}/start`, 30_000);
const wait = await post(`/containers/${SEEDER_CONTAINER}/wait`, WAIT_TIMEOUT_MS);
const { StatusCode: exitCode } = (await wait.json()) as { StatusCode: number };
if (exitCode !== 0) {
    throw new Error(`${SEEDER_CONTAINER} exited ${exitCode} — the databases are NOT in a known state.`);
}

The iOS, Android and Flutter harnesses make the same two calls.

There's one more step, and it's the subtle one. A restore tells the servers to drop their caches, but the servers get that notification asynchronously. A test that starts too soon could have one replica still holding pre-reseed data, and its app could hear the reseed mid-test.

So the seeder prints a consistency token, and the harness asks for it through the load balancer at a test-only endpoint, /api/testing/heard/{token}. It keeps asking until every instance has answered yes, counting distinct values of X-Knowby-Instance against the number of running containers. Only then does the test start.

The fault proxy: breaking real traffic on purpose

The most valuable piece of the environment is also the smallest. It's a single Python file with no dependencies beyond the standard library, about 430 lines of asyncio. In end-to-end tests it sits between the apps and the servers.

Diagram: the fault proxy's actions. status answers with any code without asking the server; delay waits then forwards; refuse closes the connection before any response; hang accepts and never answers; rewrite replaces the response body; lag holds back every streamed event; cut drops a stream partway through; drop aborts connections already open

The rule behind it is short: failures come from the fault proxy, never a mocked network. Offline, latency, HTTP errors, a dropped connection, a server outage and its recovery, retries, reconnection, and a 401 followed by a token refresh are all tested through the app's real networking code against real servers.

It replaced an earlier approach: an in-process fake of the Identity and Pro APIs with 29 scripted scenarios. A fake like that is a second, hand-maintained reading of the API. When the server changes, the fake and the app can agree with each other while both are wrong. The iOS app now has a test that fails if a stub transport ever comes back.

How it works. The proxy listens on each server's port plus 100: 3101 for Pro, 3100 for Identity, and so on. It forwards everything unchanged to the load balancer and streams responses as they arrive, so Server-Sent Events pass straight through. A control API on port 3199 takes rules. Each rule matches a service, a path pattern, optionally a method or a header, and an action, and can run once, a set number of times, or always. The first matching rule wins.

The actions cover the failures a mobile app actually meets. hang is a captive portal or a server that accepts and never replies. lag makes every event on a stream arrive late but in order. cut drops a stream partway through, as a server restart or a network change would.

Pointing the real app at it. The apps are configured with one URL, Identity's. They read every other service's URL from the organisation record, so routing an app through the proxy doesn't need a special build. One SQL UPDATE on the organisation rows sets the URLs to the proxy's ports, and the real app follows.

Failing only what you mean to. Rules can match a header. The apps mark background predownloads with a header, so a test can fail every background download while a person's own reads still succeed. That's a case no network switch could produce.

A witness. The proxy keeps a log of every request it sees, with authorisation headers, API keys and cookies redacted. Each entry includes the status, whether it's still pending, and the time to the status line. Tests assert on what the app actually sent, rather than on container logs.

A test reads like the behaviour it proves:

/// Cases: HOME-019, ERR-017.
@MainActor
func testAFailedLoadRecoversOnRetry() throws {
    let first = try XCTUnwrap(published().first)
    let app = launchReal()
    try signInAfresh(app) { try E2EFaults.fail(.pro, path: "\(Self.publishedPath)*", status: 500, times: 99) }
    app.state("home.failed").assertAppears("a failed first load shows the failure", timeout: 30)
    XCTAssertEqual(app.state("home.failed").label, "Couldn't Load Your knowbys")
    try E2EFaults.clear()
    app.buttons["home.retry"].tap()
    app.staticTexts[Self.cardID(try XCTUnwrap(first["id"] as? String))]
        .assertAppears("Retry loads the list", timeout: 30)
}

The same proxy serves the Android and Playwright suites through their own small wrappers. Real outages are tested too. A harness can stop every Identity instance through the Docker API, and the app then meets the load balancer's real 502. The restart is registered as teardown before the stop, never as a defer, because a test that stops on its first failure would never run the defer.

Silencing email without restarting anything

Locally, the servers can send real email and push notifications. That's deliberate, because the local stack is also how I check that an invitation email really looks right in a real inbox.

That capability caused a real problem. The web app's Playwright suite drove the containers, which weren't flagged as a test environment. Every invitation, CSV member import and PDF export it exercised sent real mail to a real inbox, for months, with nothing in any test run saying so.

The fix is two marker files in a runtime-flags folder. While suppress-email exists, no service sends email; suppress-push does the same for push notifications. The email and push senders check for the file on every send.

The design choices are each there for a reason:

  • A file, not an environment variable. A container's environment is fixed for its lifetime, so a variable would mean recreating eight services around every test run. That's slow, and it fails open.
  • The folder is mounted, not the file. A bind-mounted file is tied to one inode, so deleting it on the host would leave the container still seeing it.
  • Leases. Up to twelve test processes run at once, so each one writes a lease file named after its process ID. The marker goes only when the last live lease does.
  • A stale marker never expires. That's the safe direction. A marker that vanished on its own could let a long test run start mailing people again.
  • Production can't see it. The check runs only when the environment is Local. A deployed process returns on a string comparison and never touches the filesystem. Since the local stack is a Release build, #if DEBUG couldn't do this job.

Every .NET test assembly takes a lease automatically through a shared MSBuild targets file. It isn't done in a shared library's module initializer, because a referenced library's initializer runs lazily, and it didn't run at all for a test class that named no type from that library. That was measured, not guessed.

Tests at every layer, proved once

The testing rule is one sentence: test a behaviour at the lowest layer that can prove it reliably, and prove it once. Every test sets its own application, backend, database and network state, so every test is deterministic.

LayerWhereWhat is stubbed
Server integrationxUnit, against real PostgreSQL and the seedNothing below the server
API contractiOS and Android integration tests against the local stackNothing
Client unit and featureSwift Testing on iOS, JUnit 5 on AndroidOnly the transport and the auth service
End-to-end UIiOS UI tests, Android UI Automator, PlaywrightNothing
Fault injectionThe same end-to-end suites, through the fault proxyNothing: the proxy breaks real traffic

Take one behaviour: a member removed from an organisation loses access.

  • Server integration tests cover every membership state.
  • API contract tests check the shape of the 403 response.
  • Client unit tests check what the app's store does with it.
  • End to end, there's one journey, not a repeat of every case.

As of today, the counts are:

AreaTests
.NET backend24 test projects, about 2,600 xUnit facts and theories
iOS unit, feature and contractabout 2,860 tests, about 200 of them against the local stack
iOS end-to-end59 test classes, about 890 tests
Android unit, feature and contractabout 1,900 tests
Android end-to-endabout 530 tests
Web end-to-endabout 670 Playwright spec files, desktop and mobile

A few layer-specific details:

  • The server suites reset before every test in about 45 ms. Guard tests enforce architecture rules, such as every table having entity-tag columns and a trigger, and no code setting a transaction isolation level.
  • Async side effects are polled, never slept on. A helper polls until a condition holds or a timeout passes.
  • The iOS contract tests use the real HTTP client and repositories and sign in with real Firebase. They refuse to run unless the build is DEV and the host is localhost. Decoding the response is the schema assertion.
  • The Flutter app is the one client that can't fail at build time, because Dart decodes JSON at runtime, so its contract tests parse real responses from the local stack. A guard test reads every test file and fails on any non-loopback URL. Another fails if an API key appears anywhere in the tests, because a contract verified through the wrong door isn't the contract the app depends on.
  • The web suite has two fixtures that fail tests for things a person would never notice. One is a request budget: the same GET twice within 1.5 seconds, or a path read more than three times in two seconds. The other is page errors: any uncaught error, unhandled rejection or native dialog.

Sharding the test run

Diagram: twelve private test stacks share one PostgreSQL server. Each shard has its own copy of every database, its own server processes and its own test process. Measured run times: 8 shards 177 seconds, 12 shards 78 seconds, 18 shards 77 seconds

A server's integration tests can't run in parallel against one database. Every test resets the database, and each server under test reads its connection string once, at startup. So parallelism needs whole private stacks: what the runner calls shards.

To be precise about the word: this is test sharding, not production database sharding. Production keeps one database per service. A shard is a private copy of every one of those databases, plus its own set of server processes pointed at them, plus its own dotnet test process. Shards share nothing but the PostgreSQL server and the machine.

A Python script runs the whole thing:

knowby-servers/scripts/integration-tests.py up   --shards 12    # about 45 s, once
knowby-servers/scripts/integration-tests.py run  --shards 12    # about 57 s
knowby-servers/scripts/integration-tests.py down

What's inside:

  • Plain CREATE DATABASE, then the seeder. Each shard's databases are created this way and seeded. Copying from a template database would be faster, but Postgres requires the template to have no connections at all, and the dev stack's own servers hold connection pools against exactly those databases.
  • Every connection string is redirected. One database is often read under several environment variable names: the Pro server's, the jobs server's, the reporting code's. Every one has to point at the shard's copy, or the shard quietly reads the shared one. The runner writes a small per-shard override file for this. The shared environment file, which holds real credentials, is never copied.
  • Blocks of ten ports. Each shard takes ten ports from 43000 up, with the same last digit as the dev stack's ports: Identity on 0, Pro on 1, and so on. Each shard also gets its own fault proxy.
  • Weighted work. The runner splits the work by test method, packing the heaviest first, using the durations measured on the previous run.
  • Lanes. A lane is a whole separate cluster with its own ports and database names, so two git worktrees can run the suites at the same time. The Android runner uses its own lane by default, so an Android run never meets an iOS one.

The shard count was chosen by measurement, not by guessing:

ShardsWhole .NET suite
8177 s
12103 s cold, 78 s warm
1890 s cold, 77 s warm

At eight shards, the runner gives each of the nine suites one shard before handing out any second one, so the big Pro suite runs on a single shard and holds up the whole run. Past twelve, more shards buy nothing for half again the resources. The first run after a down is slower, about 75 seconds against 57, because there are no weights yet.

Sharding also exposes bugs. A test that depends on another test's leftovers fails when they land on different shards. A connection string that names a database directly instead of reading configuration escapes its shard and shows up immediately.

The mobile and web end-to-end suites use the same shards. integration-tests.py serve starts a control service on the loopback address. It can restore a shard, stop or start its Identity or Pro server, and return a server's log since a given moment: the four things a simulator can't do for itself.

On iOS, the runner pairs six backend shards with six simulators and runs each device size in turn: a small iPhone, a large iPhone, an iPad and a large iPad Pro. One simulator against the shared stack would take about 25 minutes per device. Android does the same with one emulator per shard. Playwright gives each worker its own shard and reseeds before every test in about half a second.

The runners can also select only the areas a change reaches, compared with the main branch, so an everyday run is minutes, not an afternoon.

Load testing, where it belongs

Load tests don't run against the local stack, because a development machine's numbers don't say much about production capacity. They're Grafana k6 scenarios run against the deployed test environment. The first scenario family measures the capacity of the GPU-backed Cloud Run service that turns videos into guides, with three shapes:

  • a step ramp that adds virtual users at intervals
  • a fixed soak
  • a burst
export const options = { scenarios: { studio_generator_step_ramp: {
    executor: 'ramping-vus', startVUs: START_VUS, stages: buildStages(),
    gracefulRampDown: '30s', gracefulStop: '30s' } }, thresholds: sharedThresholds() };

Each run writes its results to JSON with a one-line verdict. Locally, performance is checked in narrower ways. For example, a timing test on the home list can switch the published-list cache off through an environment variable and measure the difference.

Guards that keep the tests honest

A test suite can lie in several ways, and most of the rules here stop a specific lie:

  • An unreachable stack is a failure, not a skip. A suite that skips itself when the servers are down would report green for a run that tested nothing.
  • Every new unit and integration test is watched failing first. Break the code, see that test fail by name, restore it, and say in the pull request which change proved it.
  • A flaky test gets a cause. Never re-run until green, never add a sleep, never mark it skipped. The investigation is time-boxed to about half an hour before it goes back to the owner.
  • A failure is proved pre-existing at the merge base before anyone blames the old code for it.
  • iOS builds Release before every commit. No test compiles the #if DEBUG boundary out, so only a Release build proves it.
  • Warnings are errors. That's true on iOS and Android, including Android Lint.
  • Compile errors are watched for. A long test run is monitored for compile errors as well as test results, because a build failure prints no test lines at all. A monitor watching only for test results reports a clean run that never ran.
  • UAT cases are traced. Every end-to-end test names the UAT cases it proves, in a comment like /// Cases: HOME-019, ERR-017.. A script reads the UAT workbook directly and reports which cases no test proves yet.

No CI pipeline runs these suites. All of them run locally before a merge, against the real stack; GitHub Actions only builds the Flutter app and scans containers. That's a deliberate trade-off. The full suites need Docker, simulators, emulators and real sign-in, and running them where the developer can see and fix a failure straight away keeps the feedback loop short.

Rebuild everything, every time

One rule causes more grumbling than any other: rebuild every service, never just the one you changed.

Nearly every server links the same shared infrastructure library, so a one-file change can reach all of them. A partial rebuild produces three kinds of fake failure, and each one reads as a real bug:

  • Old containers still running old code.
  • A forgotten jobs server still running on the host, which doesn't show up in docker ps.
  • One server built newer or older than the rest, so a shared filter overwrites an entity tag with an older value.

So a rebuild is always all of them:

SERVICES="knowby-identity-api-server knowby-pro-api-server \
  knowby-media-proxy-api-server knowby-public-web-server knowby-intelligence-api-server \
  knowby-translation-api-server knowby-jobs-api-server knowby-pro-web-server"
docker compose -f docker-compose-local-no-cuda.yml build $SERVICES
docker compose -f docker-compose-local-no-cuda.yml up -d --force-recreate --no-deps $SERVICES

Afterwards, docker inspect should show every container created within seconds of each other. A compose-built image doesn't print a git commit at startup, so the creation times are the evidence.

There's a related trap. An IDE's "fast mode" can mount host-built binaries into a container. Then docker compose build changes nothing, while a dotnet build on the host does. The shared run configurations keep fast mode off. The edit-run loop is slower, but every developer's stack behaves the same way.

The handbook is also the harness

All of these rules live in the repository's CLAUDE.md files: one at the root, and one each for the servers, iOS, Android and the web. Each rule is written with the failure it prevents.

Those files serve two readers. They're the engineering handbook for anyone working on the code, and they're the instructions the AI coding agents read before every task. That's where this environment connects to harness engineering. An agent works under the same rules, against the same stack and the same proofs: rebuild everything, never run a long command silently, failures come from the fault proxy, every test watched failing first. An agent that breaks a rule finds out the way a person would, from a test that fails.

What it gives a developer

All of this is infrastructure, but its point is the day-to-day experience of working on the platform. Here's what it changes.

The whole platform from one command. A developer, or an AI agent, gets every server, the web app, the database and seeded data with docker compose up. There's no shared development server to wait for, break or queue behind, and lanes let two worktrees run full test suites side by side.

Production bugs found at the desk. The bugs that normally need production to appear can now show up locally: a cache one replica forgot to evict, an eviction path that only runs when memory is tight, a stream dropped mid-change, a garbage collector creating a thread for every core. They fail locally before they can reach a customer.

Any failure, on demand, in one line. Offline, a hanging captive portal, a burst of 500s, a stream lost halfway, a background download failing while a person's reads succeed, a server outage and its recovery. A simulator has no network switch at all, yet every one of these is a single line in a test and runs against the real app and the real servers.

Fast enough to run all the time. A reset takes about 45 ms instead of half a second. About 2,600 backend integration tests finish in under a minute on twelve shards. The mobile suites run across six simulators or emulators at once instead of one device at a time, and the runners can pick only the areas a change reaches. Tests that run in minutes get run before every commit.

A red test means a real bug. Fixed clocks, fixed data and a known state before every test mean a failure points at the code, not at leftover data or a slow network. Flaky tests get a cause instead of a re-run, so the suites stay worth trusting.

Easier debugging. The proxy's request log shows exactly what the app sent and what came back. Every response names the instance that answered. The jobs pipeline runs in-process on the host, so an AI video job can be stepped through in a debugger.

Safe by default. No production data is ever needed locally. The Docker API and the fault proxy listen only on the loopback address. Email and push are switched off while tests run, so a test can never mail a real person again.

Confidence to merge. Every layer, from server integration to end-to-end with injected faults, runs locally before a merge. By the time a change reaches UAT, its happy and unhappy paths have already been proven against the real stack.

Rules that explain themselves. Every rule in the handbook comes with the failure that caused it, so a new developer learns why things are done, not just what to do, and so does every AI agent that reads it.

If you're building one

If I were starting a local environment from scratch, these are the parts I'd build first:

  • Run several instances of every server behind a round-robin load balancer, and make every response name its instance.
  • Make the containers believe they're production-sized: cap cache memory, and check garbage collection and thread settings against the host's core count.
  • Seed through the real code, deterministically, and commit the output. Review the seeder, not the dumps.
  • Make a reset fast enough to run before every test, and wait until every instance has heard about it.
  • Break real traffic with a proxy instead of mocking the network, and point the real app at it through configuration, not a special build.
  • Put switches that must change at runtime in files, not environment variables, and make them fail safe.
  • Measure the parallelism you need before choosing it, then shard whole stacks, not just tests.
  • Write every rule down with the failure that made it, where both people and agents will read it.

None of this is exotic. It's Docker Compose, nginx, PostgreSQL, a few hundred lines of Python and a lot of measuring. What makes it work is that every piece exists because something once failed, and the environment now makes sure that failure happens locally first.

Want the detail?

Open to senior software engineering roles, contract or permanent, remote or hybrid.