Design a Test Pyramid for a Microservices Architecture
Reads a microservices topology (services + integration points) and returns a recommended pyramid distribution with concrete percentages per layer, layer-by-layer justification, explicit contract-test placement at every service boundary, and a strategy for async events.
When to use it
- Designing the test strategy for a new microservices system.
- Auditing an existing test suite that feels like an ice cream cone (too many E2E, too few unit tests).
- Justifying investment in contract testing to engineering leadership.
- Onboarding teams new to microservices testing patterns.
The prompt
<role>You are a distributed-systems test architect. You know that microservices testing fails when teams treat the pyramid as suggestive instead of prescriptive, and when contract tests get skipped because they "felt heavy". You enforce explicit percentages and explicit contract-test placement.</role> <context>Microservices pyramid: Unit (largest) → Integration (component-level) → Contract (service boundaries) → E2E (smallest). The contract layer is mandatory at every service boundary; without it, integration is just hope. E2E covers cross-cutting business journeys, not unit-level concerns. Async events (Kafka, RabbitMQ) deserve their own contract pattern.</context> <task>For the topology I provide:1. Recommend percentages per layer (sum to 100%) for the SUITE composition, not for runtime.2. Justify each layer's percentage with a 1-2 sentence rationale.3. Identify EVERY service boundary; place a contract test recommendation at each.4. Address async event boundaries with a contract pattern (event schema, Pact-style consumer-driven, or producer-driven).5. Flag any anti-pattern in the topology (mono-service called from too many places, missing API gateway, etc.).</task> <input>Topology (services + integration points): {topology}Current test suite shape (if known): {current}Team size: {team}</input> <constraints>- Percentages sum to 100%; show numbers, not L/M/H.- E2E layer is SMALLEST. If your recommendation puts E2E > 10%, justify aggressively.- Contract test at every sync boundary (HTTP, gRPC) AND every async boundary (events).- Address ice-cream-cone anti-pattern explicitly if current suite is described.- Don't recommend a tool without explaining why (Pact vs spec-based vs schema-only).</constraints> <output_format>Five sections:1. **Pyramid (ASCII diagram with percentages)**2. **Layer rationale**: one paragraph per layer3. **Contract test placement**: table: Boundary | Type (sync/async) | Recommended approach4. **Anti-patterns spotted**: bullets (or "None observed" if clean)5. **Migration path** (if current suite is provided): order to shift the mix</output_format> <approach>Before writing, count service boundaries and async streams in the topology.</approach>## RoleDistributed-systems test architect. Pyramid is prescriptive, not suggestive. Contract tests mandatory. ## ContextPyramid: Unit (largest) → Integration → Contract → E2E (smallest). Contract at EVERY boundary, sync and async. ## TaskFor the topology:1. Percentages per layer (sum 100%).2. Layer rationale (1-2 sentences each).3. Contract test at every sync AND async boundary.4. Async event pattern (consumer-driven, producer-driven, schema-only).5. Flag anti-patterns. ## Input- Topology: {topology}- Current test suite shape: {current}- Team size: {team} ## Constraints- Percentages sum 100%, numbers not L/M/H.- E2E SMALLEST; if > 10%, justify.- Contract test at every boundary.- Address ice-cream-cone if current is provided.- Tool recommendations need reasoning. ## Output format5 sections: Pyramid (ASCII + percentages) | Layer rationale | Contract placement table | Anti-patterns | Migration path (if applicable). ## ApproachCount boundaries and async streams first.Example
Input
Topology: - gateway (public-facing HTTP) - auth-service (sync HTTP from gateway, async event: UserCreated) - billing-service (sync HTTP from gateway, sync HTTP to payment-provider external) - notification-service (consumes UserCreated event, consumes BillingCharged event) - user-service (sync HTTP from gateway, publishes UserCreated event) - billing-service publishes BillingCharged event Current test suite shape: 60% E2E (slow, flaky), 20% integration, 15% unit, 5% contract. Team size: 8 engineers, 1 QA.
Output
## 1. Pyramid (target)
```
/\
/E2E\ 5%
/------\
/Contract\ 15%
/----------\
/Integration \ 25%
/--------------\
/ Unit \ 55%
/------------------\
```
## 2. Layer rationale
**Unit (55%)**: Each service has substantial logic that should be verified in isolation (auth token generation, billing rule application, notification routing). Fast, deterministic, runs on every PR. Going below 50% here puts pressure on slower layers; going above 70% suggests over-mocking and missed integration concerns.
**Integration (25%)**: Per-service integration covers DB, cache, and library boundaries. Bigger than usual here because the team is small (8 engineers, 1 QA): pushing test load into the integration layer that engineers maintain is more sustainable than pushing it into QA-owned E2E.
**Contract (15%)**: Every service boundary (3 internal sync HTTP + 1 external HTTP + 3 async event links = 7 contracts). At 15%, the suite has bandwidth to cover both sides of every boundary.
**E2E (5%)**: Only the 3-5 cross-cutting business journeys need full-system coverage: signup → first charge → notification, password reset, account suspension. E2E is for CONFIDENCE that the system as a whole works; everything else lives in layers below.
## 3. Contract test placement
| Boundary | Type | Recommended approach |
|----------|------|---------------------|
| gateway → auth-service | sync HTTP | Pact (consumer-driven, gateway as consumer) |
| gateway → billing-service | sync HTTP | Pact (consumer-driven) |
| gateway → user-service | sync HTTP | Pact (consumer-driven) |
| billing-service → payment-provider (external) | sync HTTP | Schema-only validation against vendor OpenAPI (Pact requires partner cooperation) |
| user-service → UserCreated event → notification-service | async | Pact for Async (consumer-driven from notification side) OR Avro schema registry with backward compatibility |
| billing-service → BillingCharged event → notification-service | async | Same as above; use the same pattern for consistency |
| user-service → UserCreated event → auth-service (if consumes) | async | Same |
## 4. Anti-patterns spotted
- **Ice-cream cone**: Current suite has 60% E2E. Test suite is upside-down from the recommended pyramid. This causes the slowness and flakiness described.
- **No contract layer at sync boundaries**: At 5% contract, the gateway and the services downstream can drift in interface without anyone noticing until E2E catches it (too late, too expensive).
- **No event schema validation between user-service and notification-service**: A UserCreated change to the payload would silently break notifications.
## 5. Migration path
Order of effort to flip the pyramid right-side up (assuming 3-month horizon):
1. **Cut E2E to 15-20%**: Identify the 30 highest-value E2E tests covering the cross-cutting journeys; delete the rest. Cost: 1-2 weeks of QA effort + stakeholder communication.
2. **Introduce contract tests at the 3 internal sync boundaries**: Pact with one consumer / provider pair at a time. Train 2 engineers per quarter on contract tests; ship as a service-by-service rollout. Cost: 4 weeks for first boundary, ~1 week each thereafter.
3. **Adopt event schema validation**: Use Confluent Schema Registry or similar; enforce backward compatibility in CI for both event producers. Cost: 2 weeks setup.
4. **Backfill integration tests**: Each service team adds 5-10 integration tests per quarter until the 25% target is hit.
5. **Hold unit at current ~15% during the migration, then grow to 55%**: Don't try to grow unit while changing higher layers; the chaos compounds.
End state in ~6 months: 55% unit / 25% integration / 15% contract / 5% E2E with execution time ~10x faster and flake rate near zero.Common pitfalls
- Model recommends 'balanced' 25/25/25/25 percentages: that's an anti-pattern. Force E2E < 10%.
- Contract tests get listed as 'recommended' without naming a specific approach per boundary.
- Async event testing gets glossed over: explicit async pattern is mandatory.
- Migration path skips ordering: without sequence, teams try to do everything at once and stall.
Tips
- Re-run quarterly; team and topology drift.
- Pair this prompt with `risk-based-testing-prioritization` to allocate the limited contract-test budget to the highest-risk boundaries first.
- Read Cindy Sridharan's essay 'Testing Microservices, the sane way' if your team needs deeper conviction; this prompt summarizes the principles, the essay has the war stories.
- Resist pressure to add 'just one more' E2E test. Every E2E added has compounding cost; budget enforcement is the only mechanism that works.
FAQ
When is ice-cream cone acceptable?
Rarely. The most defensible case: a UI-heavy monolith where backend is so thin that E2E covers most behavior. For microservices, ice cream cone always signals an architecture problem (services too tightly coupled to test individually).
Contract tests vs integration tests: what's the difference?
Integration tests verify your service works with its dependencies (DB, cache, etc.). Contract tests verify your service's API matches what consumers expect (or what providers promise). They cover different concerns; both are needed.
How do I migrate from a top-heavy suite?
Carefully. Don't delete E2E tests until you have contract tests covering the same boundaries: otherwise you remove safety nets faster than you build them. See the migration path in the example output.
Do I need contract tests if I have an OpenAPI spec?
An OpenAPI spec describes the contract; contract tests verify it's HONORED. Spec + no tests = honor system. The most lightweight version: validate response payloads against the spec in your integration tests.