System Design Part 10 Delivery

Testing at Scale: End-to-End Tests Cannot Carry Thirty Services

Bill.Lin 18 min read

System Design series Part 10-1 | Previous: Distributed Scheduler | Next: CI/CD and Deployment Strategies | Series map

Scenario and problem

The talk platform has been split into about 30 services (Monolith vs Microservices) and deploys a dozen or more times a day. Last quarter’s four incidents:

  1. An event field renamed: the sign-up service renamed memberId in its events to attendeeId, and all of its own tests passed. After the deploy, the notification service started throwing an exception on every event
  2. The load test passed, the sale still crashed: the load test report showed a p99 of 300 milliseconds; when sales actually opened, users waited 30 seconds
  3. Failover was never rehearsed: the Redis primary failed, the application’s connection timeout was left at its default, and the whole service was down for 20 minutes before it recovered
  4. An authorization bug came back: a refactor removed the owner condition from a query, and BOLA was live in production for two weeks (Authorization post)
Last quarter's four incidents1 / 4
Last quarter's four incidentsSign-up svcSign-up eventNotificationsLoad testRedisUsersSign-up svcSign-up eventNotificationsfield renamednew formatOwn tests all passThrows on every eventLoad testSign-up svcUsersload testp99 300 msWaited 30 s at the saleSign-up svcRedisdefault timeout, waitsPrimary downDown for 20 minutesUsersSign-up svcanother's sign-upOwner check removed
  1. An event field renamedThe sign-up service renamed memberId in its events to attendeeId, and all of its own tests passed. After the deploy, the notification service started throwing an exception on every event.
  2. Load test passed, sale crashedThe load test report showed a p99 of 300 milliseconds; when sales actually opened, users waited 30 seconds.
  3. A failover never rehearsedThe Redis primary failed, the application's connection timeout was left at its default, and the whole service was down for 20 minutes before it recovered.
  4. The authorization bug came backA refactor removed the owner condition from a query, and BOLA was live in production for two weeks.

None of these four incidents shows up in the unit tests of the service involved.

The simplest approach and its limits

Build a staging environment, deploy every service to it, run the full end-to-end test suite there, and ship only when everything passes:

  • Slow: a full end-to-end run across 30 services takes several hours, so a dozen or more deploys a day can only wait in line
  • Flaky: any one service, or any network blip, makes the tests fail. The cause of a failure often has nothing to do with the change under test, and the team gets used to “just run it again”
  • Environments interfere with each other: several teams deploy different versions to the same staging at the same time, so a test result depends on which versions of the other services happened to be there
  • Still not like production: data volume, traffic, and hardware are all much smaller than in production, so incidents 2 and 3 cannot be caught here either

End-to-end tests have their value, but they cannot be the main safety net.

Core mechanism

Each kind of test catches different problems

Level Problems it catches Run time Where it runs
Unit tests Domain logic, calculations, state transitions Milliseconds Every commit
Integration tests (real dependencies) SQL, transactions, locks, serialization, Redis scripts, Kafka configuration Seconds to minutes Every commit
Contract tests Incompatibilities between services and in event formats Seconds Every commit, on both the provider and the consumer side
Load tests Capacity, the knee in the latency curve, resource exhaustion Hours Before major changes, before large events
Fault injection and drills How timeouts, retries, circuit breaking, and failover actually behave Minutes to hours In integration tests; regularly in staging and production
A few end-to-end smoke tests Critical flows wired together end to end Minutes After deploys
Canaries and synthetic monitoring in production Problems that appear only under real traffic Continuous Production (next post)

The principle: catch each problem at the cheapest level that can catch it. Compatibility between services is checked by contract tests, not left for an end-to-end test to stumble on.

Integration tests with real dependencies

The design problems in this series rely on many database-specific behaviors: FOR UPDATE SKIP LOCKED (Distributed Scheduler), LAST_INSERT_ID(expr) (Chat System), the ascii_bin collation (URL Shortener), Redis Lua scripts and hash tags (Flash Sale Ticketing). If you stand in for MySQL with an in-memory database such as H2, these behaviors are either unsupported or have different semantics, and a passing test does not mean production is correct.

Testcontainers starts MySQL, Redis, and Kafka containers at the same versions as production during tests. The cost is speed: restarting the containers for every test class is very slow, so the containers are declared as Spring beans and, together with Spring’s test context caching, several test classes share one set of containers.

Contract tests: no need to run every service

The root cause of incident 1: the provider did not know who used which field. Consumer-driven contract tests make this explicit:

  1. The consumer writes down what it expects: “I call GET /v1/lectures/42 and need the two fields title and startsAt”, or “I read the registration-confirmed event and need memberId”
  2. The contract is published to a shared place
  3. The provider’s CI takes every consumer’s contract and verifies that its current code still satisfies them. The commit in which the sign-up service renamed memberId fails in the provider’s own CI

Common tools are Pact and Spring Cloud Contract. For event formats you can also use a schema registry’s compatibility checks:

Compatibility Guarantee Deploy order
BACKWARD New consumers can read events in the old format Upgrade consumers first
FORWARD Old consumers can read events in the new format Upgrade providers first
FULL Compatible in both directions Any order

During rolling and canary deploys, the old and new versions are live at the same time, so pick the compatibility mode by deploy order. In practice the safest rule is: only add optional fields, never rename or delete; if you really must change one, split it across several deploys (expand–contract in the next post).

Load tests: the open model and coordinated omission

Why did the load test report for incident 2 look so good? Because the load test tool used a closed model: a fixed 500 virtual users, each sending its next request only after receiving a response. When the system slowed down, the tool sent fewer requests too, the pressure dropped on its own, and the time spent waiting in queues was never measured at all. Gil Tene calls this coordinated omission: the measuring tool and the system under test “coordinate” to leave out the slowest moments.

Real users do not press the button later just because the system got slower. Traffic at a sale opening follows an open model: requests arrive at an arrival rate that has nothing to do with how fast the system responds. Flash sales, news events, and on-the-hour push notifications should all be tested with an open model.

Other points for load tests:

  • The traffic model comes from the estimates: the scale estimate at the start of each problem (Napkin Math post) is the load test’s target, including the read/write ratio and the shape of the peak
  • Data volume has to be close: with 10,000 rows in a table versus 100 million, whether the index fits in memory is a completely different story (Indexes and B+Trees)
  • Find the knee: raise the arrival rate step by step until latency starts to climb sharply. Where the knee sits is more useful than “passed at 800 requests/second” (Latency, Throughput, and p99)
  • Duration: besides short spike tests, you need soak tests lasting several hours to see connection leaks, slowly growing memory, and logs filling up the disk

Fault injection and drills

The configuration mistake in incident 3 can be found with an integration test that injects latency. Toxiproxy is a TCP proxy you control from code. It sits between the application and a dependency, and in tests it adds latency, disconnects, and bandwidth limits, so you can verify how timeouts and retries and circuit breaking actually behave.

Larger failures call for drills:

  • Chaos experiments: write down a hypothesis first (“when the Redis primary fails, the sign-up API’s error rate drops back below 1% within 30 seconds”), limit the blast radius, set abort conditions, and then actually make it fail
  • Game day: the team rehearses one scenario together, including whether the alerts fire, whether the on-call person knows what to do, and whether the runbook is correct
  • Restore drills: regularly restore from backup into a separate environment and verify the data. A backup you have never restored does not count as a backup (Redundancy, Failover, and DR)

Testing in production

Some problems appear only with real traffic, data, and configuration. Testing in production does not replace the earlier tests; it is the last layer:

  • Canary deploys: the new version first takes 1% of traffic and gets more only when the metrics look normal (next post)
  • Synthetic monitoring: every minute, a test account walks through the critical flows (log in, browse talks, sign up for a free test talk), and a failure raises an alert
  • Shadow traffic: copy production requests to the new version and compare the responses, but discard the new version’s responses. Requests with side effects (payments, emails) cannot be copied as they are; in the new version, replace the external calls with something that only records them

Comparing options

Decision Choice Alternatives given up, and why
Main safety net Unit + integration with real dependencies + contract tests End-to-end tests as the main net: slow, flaky, environments interfere with each other
Dependencies in integration tests Testcontainers, same versions as production In-memory databases: different semantics; a shared test database: tests interfere with each other
Compatibility between services Consumer-driven contracts, schema compatibility checks Relying on documentation and communication: that is exactly how incident 1 happened
Load test model Open model, injecting by arrival rate Closed model: pressure drops on its own when the system slows, so results are too optimistic
Failures Inject latency in integration tests; regular drills Waiting for it to really happen: a runbook run for the first time always has mistakes

In Java

1. Shared containers

java
@TestConfiguration(proxyBeanMethods = false)
public class TestContainersConfig {

    @Bean
    @ServiceConnection
    MySQLContainer<?> mysql() {
        return new MySQLContainer<>("mysql:8.4");                              // same version as production
    }

    @Bean
    @ServiceConnection
    KafkaContainer kafka() {
        return new KafkaContainer(DockerImageName.parse("apache/kafka:4.0.0"));
    }
}
  • The containers are beans, and Spring manages their lifecycle; tests that import the same configuration class share the cached context, and so share one set of containers
  • @ServiceConnection lets Spring Boot create ConnectionDetails from the container’s connection information, so you do not set the JDBC URL and bootstrap servers by hand
  • KafkaContainer is the newer class in the org.testcontainers.kafka package for the apache/kafka image

2. Verifying SKIP LOCKED on a real MySQL

The correctness of the Distributed Scheduler depends on “tasks never overlap when several machines claim tasks at the same time”, and that can only be verified on a real MySQL:

java
@SpringBootTest
@Import({TestContainersConfig.class, TaskPollerConcurrencyTest.RecordingHandler.class})
class TaskPollerConcurrencyTest {

    @Autowired TaskPoller poller;
    @Autowired JdbcClient jdbc;
    @Autowired RecordingHandler recorder;

    @BeforeEach
    void cleanTasks() {
        jdbc.sql("DELETE FROM scheduled_task").update();              // the shared container may hold tasks left by other tests
    }

    @Test
    void eachDueTaskRunsExactlyOnceAcrossConcurrentPollers() throws Exception {
        for (int i = 1; i <= 1_000; i++) {
            jdbc.sql("""
                            INSERT INTO scheduled_task (id, task_type, dedup_key, payload, run_at, status, created_by)
                            VALUES (:id, 'RECORDING', :key, '{}', NOW(3) - INTERVAL 1 SECOND, 'PENDING', 'test')
                            """)
                    .param("id", i).param("key", "test:" + i)
                    .update();
        }

        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {          // simulate 4 machines claiming at once
            List<Callable<Void>> pollers = Collections.nCopies(4, () -> {
                poller.poll();
                return null;
            });
            for (Future<Void> f : pool.invokeAll(pollers)) {
                f.get();
            }
        }

        await().atMost(Duration.ofSeconds(30)).untilAsserted(() ->
                assertThat(recorder.counts())
                        .hasSize(1_000)
                        .allSatisfy((id, count) -> assertThat(count).isEqualTo(1)));
    }

    @Component
    static class RecordingHandler implements TaskHandler {

        private final Map<Long, Integer> counts = new ConcurrentHashMap<>();

        @Override
        public String type() {
            return "RECORDING";
        }

        @Override
        public void handle(Task task) {
            counts.merge(task.id(), 1, Integer::sum);
        }

        Map<Long, Integer> counts() {
            return counts;
        }
    }
}
  • The background @Scheduled job also claims tasks at the same time, which simply adds one more competitor
  • Remove SKIP LOCKED and the test usually still passes, only slower (the pollers wait on each other); remove the UPDATE done when claiming tasks and the test fails (the same task runs more than once). A well-written integration test has to catch the latter

3. Authorization regression tests

The defense against incident 4: for every resource that “belongs to a member”, test that another member gets a 404 when accessing it. Add one more test to make sure a new endpoint is never left off this list:

java
@SpringBootTest
@AutoConfigureMockMvc
@Import(TestContainersConfig.class)
class OwnershipRegressionTest {

    static final List<String> OWNED_RESOURCES = List.of(
            "/v1/registrations/{id}",
            "/v1/orders/{id}",
            "/v1/conversations/{id}/messages",
            "/v1/notifications/{id}");

    static final List<String> PUBLIC_RESOURCES = List.of(             // explicitly public, owned by no member
            "/v1/lectures/{id}",
            "/v1/speakers/{id}");

    @Autowired MockMvcTester mvc;
    @Autowired TestFixtures fixtures;

    static Stream<String> ownedResources() {
        return OWNED_RESOURCES.stream();
    }

    @ParameterizedTest
    @MethodSource("ownedResources")
    void anotherMemberGetsNotFound(String template) {
        long alice = fixtures.newMember();
        long bob = fixtures.newMember();
        long resourceId = fixtures.createOwnedBy(alice, template);

        assertThat(mvc.get().uri(template, resourceId)
                        .param("afterSeq", "0")
                        .with(jwt().jwt(j -> j.subject(Long.toString(bob)))))
                .hasStatus(404);                                                 // not 403: do not reveal whether the resource exists
    }

    @Test
    void everyEndpointWithAnIdIsCovered(
            @Autowired @Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mappings) {
        Set<String> withId = mappings.getHandlerMethods().keySet().stream()
                .flatMap(info -> info.getPatternValues().stream())
                .filter(pattern -> pattern.contains("{id}"))
                .collect(Collectors.toSet());

        Set<String> classified = new HashSet<>(OWNED_RESOURCES);
        classified.addAll(PUBLIC_RESOURCES);
        assertThat(classified).containsAll(withId);                              // fails when a new endpoint is on neither list
    }
}
  • 401 and 403 are handled by the Spring Security configuration; this test focuses on object-level authorization: logged in, but not the owner
  • Public resources (talk and speaker pages) belong to no member and are listed in PUBLIC_RESOURCES. If a new endpoint is on neither list, the test fails: “forgot to classify it” is itself a bug

4. Load testing the flash sale: the open model

java
public class FlashSaleSimulation extends Simulation {

    HttpProtocolBuilder httpProtocol = http.baseUrl("https://perf.lectures.example.com");

    // Synthetic accounts only for load tests; each row is used once (the default queue strategy), so there must be more rows than the total injected users (about 680,000)
    FeederBuilder<String> members = csv("perf-members.csv");

    ScenarioBuilder buyer = scenario("Flash sale purchase")
            .feed(members)
            .exec(http("Sale status").get("/v1/flashsale/42/status").check(status().is(200)))
            // Admission tokens expire in 2 minutes and are single-use, so they cannot be pregenerated in the CSV; obtain them in the scenario
            .exec(http("Get admission token").post("/v1/flashsale/42/admission")
                    .header("Authorization", "Bearer #{accessToken}")
                    .check(status().is(200), jsonPath("$.token").saveAs("admissionToken")))
            .exec(http("Reserve").post("/v1/flashsale/42/reservations")
                    .header("Authorization", "Bearer #{accessToken}")
                    .header("X-Admission", "#{admissionToken}")
                    .check(status().in(202, 409, 410)));          // processing, already reserved, and sold out are all normal business outcomes

    {
        setUp(buyer.injectOpen(
                        rampUsersPerSec(100).to(2000).during(60),   // the waiting room lets people in gradually
                        constantUsersPerSec(2000).during(300),
                        stressPeakUsers(20000).during(10)))         // a sudden spike when the admission controller misfires
                .protocols(httpProtocol)
                .assertions(
                        global().responseTime().percentile(99.0).lt(500),
                        global().failedRequests().percent().lt(0.1));
    }
}
  • injectOpen injects virtual users by arrival rate, whether or not earlier requests have been answered; that is the open model
  • 409 and 410 count as successful check results: the load test’s “failure rate” should count only system errors, not “did not get a ticket”
  • In the real flow, an admission token can be obtained only after your queue number has been let in; the load test environment sets the waiting room to let everyone in immediately, to test the reservation and database write path specifically, and the waiting room itself is tested separately. If you pregenerate tokens in the CSV, they all expire within a few minutes, and the load test measures only the “invalid token” error path
  • The last stage deliberately injects a peak above the design, to see whether the system rejects gracefully (quickly returning 429 or 503) or locks up entirely

The code above is written from the official documentation for Spring Boot 4.1 (Testcontainers integration, @ServiceConnection), Spring Framework 7 (MockMvcTester), Spring Security Test, Testcontainers 2.0, and the Gatling Java DSL, and has not been compiled or run. TestFixtures is an illustrative component.

Pitfalls and gotchas

  • Running integration tests on an in-memory database: the tests pass, and SQL behaves differently in production
  • Restarting containers for every test class: the test run goes from a few minutes to an hour, and in the end nobody wants to run it locally
  • The provider changes a field and runs only its own tests: consumers find out after the deploy
  • Closed-model load tests: the slower the system, the lower the pressure, and the better the report looks
  • Too little data in the load test environment: all the data sits in memory, and production’s disk I/O is never tested
  • Testing only spikes, not endurance: a connection leak takes hours to show up
  • Failover that exists only in documents: the first time it really happens, you find out the runbook’s commands are out of date
  • Habitually rerunning flaky tests: real intermittent bugs (race conditions) get ignored along with them. Quarantine flaky tests and fix them; do not keep rerunning them indefinitely

Security

  • Test data must not be a copy of production data: access control in staging is usually looser than in production, so personal data copied there widens the exposure to a leak. Use synthetic data; when you really need the distribution of production data, use irreversible masking, and reassess whether the masked data can be re-identified
  • Test backdoors must not reach production: /test/reset-database, “skip the CAPTCHA in test mode”, hard-coded master tokens: exclude all of them through build configuration, not just a runtime switch; the production build needs tests that confirm these endpoints do not exist
  • Accounts for load tests and synthetic monitoring: mark them clearly as test accounts, give them the least privilege, keep them out of real lotteries and points, and exclude them from operations reports
  • Coordinate before load testing production: without notice, the WAF and abuse prevention (8-5) will block the load test as an attack, or worse, the security team will ignore a real attack as a load test
  • Authorization tests and security scans on every commit: object-level authorization regression tests, vulnerability scans of dependencies, and secrets scans run automatically in CI, instead of relying on manual checks before release
  • Staging is not safe just because it is internal: because it is “only a test environment”, staging is often exposed to the internet, uses weak passwords, or has TLS turned off. It shares code and some configuration with production, so attackers can find production’s weaknesses there

When to use it, and when not to

  • Unit tests: all domain logic, the more the better, because they are the cheapest
  • Testcontainers integration tests: all code that talks to a database, cache, or message queue
  • Contract tests: when services depend on each other through APIs or events and different teams deploy them independently; for a handful of services owned by one team and deployed together, the cost may exceed the benefit
  • Load tests: before large events, after architecture changes, during capacity planning; they do not need to run on every commit
  • Chaos experiments: only after you have observability and automated recovery; injecting faults into a system that does not even have alerts only manufactures incidents
  • End-to-end tests: keep only a few of the most critical flows, as smoke tests after deploys

References

Comments