Architectural Patterns and Anti-Patterns Questions
Architecture-level patterns and the anti-patterns that signal a wrong turn. Patterns: layered and n-tier architecture, including where cross-cutting concerns like authentication, rate-limiting and tracing belong, dependency injection trade-offs, and thin-versus-fat controller design; hexagonal (ports and adapters) and clean architecture; CQRS and event sourcing; backend-for-frontend; plugin (microkernel) extension models; and the coupling, cohesion, encapsulation and separation-of-concerns principles behind them, including when each applies and what it costs. Anti-patterns: distributed monolith, chatty services, shared-database coupling, cyclic service dependencies, leaky abstractions that expose internal schemas, and golden-hammer pattern adoption. Covers the detection signals (deploy coupling, call-graph fan-out, change amplification, trace evidence), incremental remediation, and architecture governance that keeps smells from recurring. This is about diagnosing and fixing the smell in an existing design, not the monolith-versus-microservices decision itself.
Compare layered (three-tier) architecture with hexagonal (ports-and-adapters) and clean architecture. When would you recommend a layered approach over hexagonal or clean, and what are the trade-offs in testability, adaptability to changing I/O, and team boundaries?
Sample Answer
Direct answer
All three separate business logic from input and output code; they differ in which way the dependencies point. In a classic layered architecture, presentation depends on business logic, which depends on data access, so the business layer knows about the database code beneath it. In hexagonal (ports and adapters) architecture, the business core defines interfaces called ports for what it needs and offers, and adapters (HTTP controllers, database code, message consumers) plug into them, so the database code depends on the core instead. Clean architecture is the same inward-pointing rule with more named rings (entities, use cases, interface adapters, frameworks). Recommend layered for CRUD-heavy services with one UI and one database; move to hexagonal when the service has several ways in or out or a domain worth protecting; reserve full clean architecture for large, complex, long-lived domains.
The key difference: direction of dependency
flowchart TB
subgraph Layered
P1[Presentation] --> B1[Business]
B1 --> D1[Data access]
end
subgraph Hexagonal
H[HTTP adapter] --> Core[Domain core with ports]
K[Queue adapter] --> Core
PG[Postgres adapter] --> Core
end
In the hexagonal half, the Postgres adapter points to the core because it implements a port the core declared (for example PriceRuleStore). That is the dependency inversion principle: high-level policy does not depend on low-level detail; both depend on an abstraction owned by the policy.
- Driving (primary) adapters call into the core: REST controllers, CLI, message consumers.
- Driven (secondary) adapters are called by the core through ports: databases, payment APIs, email.
- Clean architecture's rings: entities (the core business objects and rules that would still make sense even outside this app, such as an
Orderand how its total is computed), use cases (the app-specific steps that orchestrate entities to do one thing, such as "place an order"), interface adapters (translators at the edge: controllers turn an incoming request into a use-case call, presenters format a use case's result for display, gateways implement a port, such as talking to a database), frameworks and drivers (the outermost layer: the actual web framework and database driver code). Its dependency rule: source-code dependencies only point inward.
Comparison on the three asked axes
| Axis | Layered | Hexagonal | Clean |
|---|---|---|---|
| Testability | Business layer imports concrete data classes, so tests need a database or mocks of concrete classes | Core tested with in-memory fakes of each port; no framework needed | Same as hexagonal, plus use cases testable without presenters |
| Adaptability to changing I/O | New input or store tends to ripple into the business layer | New adapter implements an existing port; core unchanged | Same, with more formal boundaries for each I/O type |
| Team boundaries | Invites horizontal ownership (a UI team, a backend team, a data team), so every feature crosses every team | Port interfaces are stable contracts: one person builds an adapter while another changes core rules | Most boundaries, useful for large teams on one codebase, heavy for small ones |
| Ceremony and cost | Lowest; every framework tutorial uses it | Moderate: interfaces and mapping between domain and adapter models | Highest: request and response models, presenters, gateways per use case |
| Learning curve | Everyone knows it | Short once the port idea clicks | Long; teams often misapply the ring names |
Both team-boundary points are within one service's codebase. Which services a team owns is a separate decision; these patterns shape how people collaborate inside one codebase.
Worked example: a pricing service
Requirements: price rules are stored in PostgreSQL; competitor prices come from a partner HTTP API; prices are requested over REST, by a nightly batch file and, next quarter, from a Kafka topic (a named event stream in Kafka, a distributed message queue other services publish to and read from).
- Layered.
PricingServiceimportsPostgresRuleDaoandPartnerHttpClientdirectly. Unit-testing a price rule means starting a database or mocking two concrete classes. Adding the Kafka input means another entry point calling into a service already shaped around the REST request object. - Hexagonal. The core declares 2 driven ports (
PriceRuleStore,CompetitorPriceFeed) and 1 driving port (QuotePrice). REST, batch and Kafka are 3 driving adapters; Postgres and the partner client are 2 driven adapters. Adding Kafka next quarter touches 0 core files. Price rules get fast tests with in-memory fakes of both driven ports. - Cost, counted for one new field. In the layered version, adding
currencytouches roughly the request DTO (data transfer object), controller, service, entity, DAO (data access object, the class that talks to the database for one table) and migration (the schema-change script that applies the new column): 6 places. In a strict clean-architecture version it also touches the use-case request and response models, the presenter and one or more mappers, roughly 10. The exact count depends on the codebase, but the direction is the point: more boundaries, more mapping per change.
Recommendation for this service: hexagonal. It has three driving inputs and two external dependencies, which is exactly where ports pay back. Full clean architecture would add presenter and use-case-model ceremony without a second UI to justify it. A thirty-endpoint internal admin CRUD service would get plain layered, perhaps with a repository interface owned by the business layer as a cheap middle step.
What would flip it: if the service stays at one input and one database for its life, hexagonal's extra interfaces are ceremony. If the domain grows complex enough that several teams work in the same codebase, clean architecture's stricter rings start to earn their cost.
Pitfalls
- Hexagonal in name only. Port interfaces that return ORM entities (the database-mapped objects an object-relational mapper generates, such as a Hibernate or Active Record model) or HTTP types leak the adapter into the core; the core then depends on the framework anyway.
- One port per table. Ports should describe what the domain needs ("find active rules for SKU", a stock keeping unit, the code that identifies one specific product), not mirror the schema.
- Pattern as a golden hammer. Applying clean architecture to a CRUD service produces many files that only copy fields between near-identical objects.
- Layered done lazily. Letting presentation code skip the business layer and query the database directly ("layer skipping") removes the one benefit layering had.
Design an architectural governance process to detect and prevent anti-patterns (like distributed monoliths, chatty services, or shared databases) before they take hold at scale. What review checkpoints, health metrics, and enforcement mechanisms would keep this from becoming a bottleneck for teams?
Sample Answer
Direct answer
I would build governance as automation first, humans for the few decisions that are expensive to reverse. Most anti-patterns leave machine-detectable evidence (a service reading another service's tables, a call chain that keeps getting deeper, services that always deploy together), so those checks run continuously in CI (continuous integration: the automated pipeline that builds and tests every change before it is allowed to merge) and against production telemetry, the way tests do, and they give teams a fast, objective answer. Human review is reserved for a small set of triggers, such as a new service, a new cross-team synchronous dependency or a new shared datastore, and it runs with a published turnaround time so it never becomes a queue. Every rule has an owner, a metric, and an exception process with an expiry date.
Quick definitions of the three smells named in the question: a distributed monolith is a set of services that cannot be changed or deployed independently, so you pay the cost of a network without getting independence; chatty services make many small calls to each other to serve one request; a shared database is two or more services reading and writing the same tables, so neither can change its schema alone.
Why governance usually fails
Two failure modes, and the design has to avoid both:
- The architecture review board as a gate. Every change waits for a weekly meeting. Teams learn to route around it (calling a new service a "module", skipping the form), and the smells arrive anyway, just undocumented.
- Principles on a wiki. "Services must own their data" is written down and never checked. Six months later four services share an orders table.
The answer is to turn principles into fitness functions: automated checks that measure whether the architecture still has a property you care about, run as often as tests.
The process
flowchart TB
PR[Pull request or infra change] --> F[Fitness functions in CI]
F -->|pass| Merge[Merge]
F -->|violation| X{Approved exception on file?}
X -->|yes, not expired| Merge
X -->|no| Block[Build fails with rule link]
PR --> T{Hits a review trigger?}
T -->|no| Merge
T -->|yes| ADR[Architecture decision record plus async review, 3-day turnaround]
ADR --> Merge
Prod[Production traces and deploy log] --> H[Weekly health report per team]
H --> Q[Quarterly review of worst trends]
1. Review checkpoints (few, triggered, time-boxed)
Review is triggered by the kind of change, not by every change:
| Trigger | Why it matters | Output |
|---|---|---|
| New service proposed | Wrong boundaries are the root of chatty and god services (a god service is one service that has absorbed far more responsibility, and far more of the codebase's inbound calls, than any one team can safely own) | ADR with the capability owned and the data it owns |
| New synchronous dependency between teams | Each one adds a runtime and deploy coupling edge | ADR stating why an async event or local data copy will not do |
| Any service granted access to another's datastore | The shared-database anti-pattern starts here | Default answer is no; exception needs an end date |
| New shared library carrying domain types | Lockstep upgrades across consumers | ADR, owner, versioning policy |
An ADR (architecture decision record) is a one-page document: context, decision, alternatives considered, consequences. It is written by the team, reviewed asynchronously by one architect from a rotating pool (plus a peer from an affected team), and approved or pushed back within 3 working days. If the reviewer misses the deadline, the decision stands as written. That default is what stops review from becoming a bottleneck.
2. Automated checks (the enforcement layer)
Each anti-pattern maps to a check with a concrete data source:
| Anti-pattern | Check | Data source |
|---|---|---|
| Shared database | No service's database credentials can reach another service's schema | Database grants, infrastructure-as-code (defining and provisioning infrastructure, here database permissions, through versioned config files rather than manual changes) definitions, scanned in CI |
| Chatty services | Per endpoint, count of downstream calls per inbound request; alert above a threshold (say 10, chosen because this system's own traces show a typical endpoint makes 3 to 6 downstream calls, so 10 sits clearly above the busiest normal case, about 1.7 times the top of that range, not the full double it can read as) or a 25% rise over the previous release (which catches a regression even on an endpoint whose steady-state fan-out is already high) | Distributed traces (for example OpenTelemetry spans) |
| Cyclic dependencies | The service call graph has no cycles; a new edge that closes a cycle fails | Call graph built from traces or declared dependencies |
| Distributed monolith | Co-deploy rate: share of releases in which a service had to ship together with another | Deploy log |
| Leaky internal schema | Public API schemas may not reference internal table or entity types | Schema linting (an automated check that a schema definition follows a set of rules, run here against the public API's own schema file) on API definitions |
| God service | Number of distinct teams committing to one service per quarter; count of inbound dependencies (how many other services call it) | Version control history, call graph |
Concretely, one of these compiles to an actual query: the shared-database check runs something like SELECT grantee, table_schema FROM information_schema.role_table_grants WHERE table_schema NOT IN (SELECT owned_schema FROM service_registry WHERE service = grantee) against the database's own permission tables, expecting zero rows back; any row it returns names one real illegal grant, and CI fails the build listing it. The other rows in the table above compile the same way, into a database query, a static-analysis pass over the declared call graph, or a schema-linter rule, each with a pass condition as concrete as this one.
3. Health metrics (trends, not gates)
Some signals are too noisy to block a build but are exactly what leadership should watch. A weekly per-team report shows:
- Co-deploy rate (target below 10% of releases).
- Median and p95 (95th percentile) synchronous call depth (how many services deep a chain of blocking calls goes before the original request can complete) per user-facing request.
- Count of cross-service database grants (target zero, trending down).
- Count of open exceptions and how many are past their expiry.
- Delivery outcomes, so architecture is tied to results: deployment frequency and change lead time (two of the DORA metrics, from the DevOps Research and Assessment programme).
4. Enforcement with a ratchet
A new rule never starts as a hard block on a codebase that already violates it, or every team is instantly red:
- Measure: run the rule in report-only mode, publish the baseline (for example, 14 cross-service database grants today).
- Ratchet: the build fails if the number increases. Existing violations are grandfathered (excused from the new rule for now, because they predate it, but only as a dated, tracked exception, not a permanent pass) as dated exceptions.
- Burn down: each exception has an owner and an expiry; expired exceptions show in the weekly report and in quarterly planning.
- Harden: once the baseline hits zero, the rule becomes an absolute block.
Worked example: rolling out the "no cycles" rule
Suppose the trace-derived call graph for 40 services has 3 cycles, involving 7 services.
- Week 1: the check runs report-only; the 3 cycles are listed with the teams that own each edge.
- Week 2: the ratchet goes live. A pull request adding a call from Notifications to Orders would close a 4th cycle (Orders already calls Notifications), so it fails with a link to the rule and two suggested alternatives: Notifications subscribes to an
OrderPlacedevent, or Orders includes the needed fields in the call it already makes. - The 3 existing cycles become exceptions expiring in two quarters, placed on the owning teams' roadmaps.
- Two quarters later: if 2 of the 3 are gone and 1 remains, the remaining one is escalated in the quarterly review with a choice: fix, merge the two services (a cycle often means they were one capability), or extend with a written reason.
Keeping it from becoming a bottleneck
- Paved road over permission: publish templates (service skeleton with tracing, contract tests, its own database) so the compliant path is also the fastest path.
- Federated reviewers: one architect per group of teams, on rotation, not a central board.
- Time-boxed defaults: silence after the deadline means approved.
- Measure the process itself: median ADR turnaround and share of builds blocked by governance rules. If blocked builds exceed a few percent, the rules are too strict or too noisy and need tuning.
Pitfalls
- Metrics as targets without context. A team can cut "calls per request" by merging two endpoints into one god endpoint (the same god-service problem named above, now at the endpoint level: one endpoint absorbing so many responsibilities that it becomes the new coupling point). Review trends together with the ADRs that explain them.
- Rules without owners. A fitness function nobody maintains starts flapping (passing and failing intermittently on the same code, for reasons unrelated to whether the rule is actually being violated), teams add it to an ignore list, and the governance erodes silently.
- Governing everything. If every schema change needs review, the important reviews drown. Scope review to decisions that are expensive to reverse.
In a layered backend, concerns like authentication, rate-limiting, and tracing apply to nearly every request. If each service implements them independently you get drift and duplicated bugs. Where architecturally should this kind of cross-cutting logic live, what are the trade-offs of the placement options, and how do you keep the behavior consistent as new services are added?
Sample Answer
Direct answer
Put each cross-cutting concern at the outermost place that has enough information to do it correctly, and make that place shared infrastructure rather than per-service code. Concretely: verify end-user identity and enforce per-client rate limits once at the edge (an API gateway), secure service-to-service traffic in the platform (a service mesh: a dedicated network layer, usually a fleet of per-service proxies plus a shared control plane, that handles this uniformly, or equivalent), and keep only the parts that need business context inside each service, delivered through one shared, versioned middleware library. Consistency then comes from a paved-road service template plus automated conformance checks, not from asking every team to remember.
Cross-cutting concern means behaviour that applies to nearly every request regardless of what the request does (identity, throttling, tracing, logging). Copying it into every service is how you get the drift the question describes.
The placement options
| Option | What it is | Strength | Cost |
|---|---|---|---|
| Copy per service | Each team writes its own | Full local control | Drift, duplicated bugs, N places to patch a security fix |
| Shared library / middleware | One package every service imports; runs in-process as request middleware | Sees business context; cheap at runtime | Tied to a language; upgrades roll out service by service, so versions skew |
| API gateway | A single entry point in front of all services that inspects every external request | One deploy fixes all services; blocks bad traffic before it costs anything | Extra hop; a shared choke point; tempts teams to put business logic in it |
| Sidecar / service mesh | A proxy deployed next to each service instance (a sidecar) that handles its network traffic; a service mesh is the fleet of these plus a control plane (the piece that configures every sidecar with routing rules, security policy and certificates, so operators manage one thing instead of each proxy individually); Istio and Linkerd are example service-mesh products that bundle both | Language-agnostic service-to-service security and telemetry | Operational complexity, per-pod (per Kubernetes pod, the group of containers deployed and scaled together) CPU and memory overhead, a new failure point |
| Managed platform service | Identity provider, managed secrets, managed tracing backend | Someone else runs the hard part | Vendor coupling, less control |
Where each of the three concerns should live
Authentication (who is calling).
- Edge: the gateway validates the end-user token (a JWT, JSON Web Token: a signed token carrying the user's identity and expiry) once, rejects bad ones, and forwards the verified identity.
- Between services: mTLS (mutual TLS, where both sides present certificates so each proves its identity) issued by the mesh, so a service knows which service is calling it.
- Inside the service: a thin shared middleware still checks that the forwarded identity is present and meant for this service. This follows zero trust: never trust a request merely because it arrived from inside the network.
- Authorization ("may this user read this invoice?") stays in the service, because only the service knows who owns the invoice. Pushing that into the gateway is how gateways grow into god services (services that have absorbed so many unrelated responsibilities that no one can change them safely).
Rate limiting.
- Per-client quotas ("each API key gets 600 requests per minute") belong at the gateway, backed by a shared counter.
- Self-protection limits ("this service accepts at most 200 concurrent requests") belong in the service or its sidecar, because they depend on that service's own capacity.
Tracing (recording each request's path across services as a tree of timed spans, where each span is one unit of work, such as one service handling one call, with its own start time and duration).
- It must be partly in-process. A sidecar can time each network hop, but it cannot see work inside the process, and it cannot connect an inbound request to the outbound calls it causes unless the application forwards the trace context header (the W3C
traceparentheader, which carries the trace ID and current span ID so the next hop can attach itself to the same trace). So the shared library must include OpenTelemetry (the vendor-neutral standard and SDK for traces, metrics and logs) instrumentation that propagates context automatically.
flowchart LR
C[Client] --> G[API gateway: verify JWT, per-client quota]
G --> P1[Sidecar: mTLS]
P1 --> S1[Service A: shared middleware, authz, tracing SDK]
S1 --> P2[Sidecar: mTLS]
P2 --> S2[Service B: shared middleware, authz, tracing SDK]
Worked example: two numbers that decide placement
Distributed rate limits. A 600 requests-per-minute limit per API key is configured on 3 gateway replicas, each counting locally. A client whose traffic is spread round-robin across replicas can send up to 3 x 600 = 1,800 requests per minute before any replica says no. Fixes: keep the counter in a shared store such as Redis (a fast, shared in-memory data store), or give each replica 600 / 3 = 200 and accept that uneven routing will throttle some clients early. Placing the limit "in the gateway" is not enough; where the counter lives is part of the design.
Patch latency. Say 40 services depend on an auth library and a token-validation bug is found. If teams upgrade at about 5 services a week (an assumption; measure your own), full coverage takes 40 / 5 = 8 weeks, during which some services are still vulnerable. The same fix in the gateway is one deploy. That asymmetry is why token validation belongs at the edge and the library only double-checks.
Keeping it consistent as services are added
- Paved road (a default, pre-wired path that is easier to follow than to deviate from). New services start from a template that already wires in the middleware, the tracing SDK and the mesh annotations (configuration labels attached to a service that tell the mesh's control plane how to handle its traffic). The easy path is the correct path.
- Minimum-version policy. CI (continuous integration) fails a build whose shared-library version is older than the supported floor, which turns skew into a visible, bounded window.
- Policy as code. Gateway routes, rate-limit rules and mesh authorization policies live in one reviewed repository, not in consoles.
- Conformance tests. An automated check hits every newly registered service without a token and expects 401, and checks that its spans appear in the trace backend. This is an architecture fitness function: an automated test of an architectural property.
- Clear ownership. A platform team owns the gateway, mesh and library; product teams own authorization and business rules.
Trade-offs and pitfalls
- Gateway creep. Once authentication lives in the gateway, teams add request transformation, then business rules, and the gateway becomes a god service every team must change. Keep it domain-agnostic.
- Edge-only security. If services trust any request that reached them, one compromised internal service can impersonate everyone. Keep mTLS and in-service identity checks.
- Mesh adoption for one concern. Adopting a service mesh only to get tracing is golden-hammer thinking (reaching for one favourite tool for every problem, regardless of fit); the SDK does most of that. Adopt a mesh when you need uniform mTLS and traffic policy (rules for how requests are routed, retried and load-balanced) across many languages.
- What would flip the recommendation: a small system with 3 services in one language does not need a gateway or mesh; a single shared middleware library plus a service template is enough.
Your team moved to microservices, but engineering velocity has stalled: releases need cross-team coordination, on-call keeps getting paged for cascading issues, and a schema change in one service quietly breaks two others. Which architectural anti-patterns do you suspect are at play? For each one, give a concrete detection signal you'd look for in monitoring or traces, and one pragmatic, incremental remediation step.
Sample Answer
Direct answer
Those three symptoms point to six suspects, including one that is worth checking even though it does not map cleanly to a single symptom below. Lockstep releases suggest a distributed monolith: services that are packaged and deployed separately, so they look like microservices, but are coupled tightly enough that they still have to change and ship together, the coordination cost of a monolith without the deployment independence a microservice split is supposed to buy. Cascading pages (one service's trouble tripping alerts through several other services it calls, or that call it, in a chain) suggest chatty services and long synchronous call chains, possibly with cyclic dependencies. A god service, one service that has absorbed so many responsibilities that it shows up in almost every trace and almost every incident, is that additional suspect: it can force lockstep releases because every dependent team waits on the team that owns it, and it can make pages cascade because it sits on the path of most requests. A schema change breaking two other services points to shared-database coupling or a leaky abstraction (an interface meant to hide a service's internal details, that lets them show through anyway) that exposes one service's internal schema to others. Confirm each with evidence from traces, deploy history and database access logs before acting, then fix incrementally, starting with the one that causes the most pages. Do not propose a rewrite.
Symptom to anti-pattern, detection signal and first remediation step
| Symptom | Suspected anti-pattern | Detection signal | One incremental remediation |
|---|---|---|---|
| Releases need cross-team coordination | Distributed monolith: independently deployed services that must still ship together | Deploy coupling: share of releases where 2 or more services had to deploy in the same window for one change; co-change in version control (the same ticket touching several repositories) | Make API changes backward compatible (add fields, never rename or remove in one step) and add consumer-driven contract tests (each consumer publishes the requests it relies on; the provider's CI fails if it breaks them), so each service can ship alone |
| On-call paged for cascading issues | Chatty services: many fine-grained calls to render one result | Trace span count per user request and fan-out (how many downstream calls one request triggers); many sequential calls to the same service inside one trace (the N+1 pattern: one call to fetch a list, then one extra call per item in that list, instead of a single batched call) | Replace the loop of per-item calls with one batch endpoint (GET /prices?ids=...), or keep a local read-only copy of slowly changing reference data |
| Same cascade, pages across many teams | Cyclic service dependencies: A calls B, B calls C, C calls A | Build the service call graph from trace data and look for cycles; a single incident paging several teams' services in a loop | Break one edge of the cycle: move the back-call to an event the upstream service publishes, so the dependency points one way |
| One service appears in almost every trace | God service: one service that owns too many responsibilities | High in-degree (a graph term for many incoming edges, here meaning many other services call into it) in the call graph; one repository with commits from many teams; its deploys correlate with others' incidents | Carve out the single most frequently changed responsibility behind its own interface first |
| Schema change in one service breaks two others | Shared-database coupling | Database logs or per-role query statistics (usage broken down by database login/credential, not by job role) showing several services' credentials reading or writing the same tables; incidents in other services following a migration | Give each table exactly one owning service; as a first step, publish a read-only database view or an API as the stable contract and move readers onto it |
| Same, via the API or events | Leaky abstraction exposing internal schema | API responses or events whose field names mirror table columns; change-data-capture streams (a feed of every row-level insert, update and delete, read straight off the database) of raw tables consumed directly by other teams | Introduce an explicit, versioned public model and map the internal schema to it, so internal columns can change freely |
Span: one timed operation in a distributed trace, such as one HTTP call. Trace: the tree of spans produced by one user request.
Worked example: putting numbers on the cascade
A checkout trace shows one user request producing 23 spans (a span is one timed operation in the trace, such as one HTTP call; 23 means some services are called more than once) across 7 services, with 6 of the calls made one after another, which is what makes the request slow. Separately from that latency picture, checkout's correctness depends on all 7 services succeeding, whether a given call sits on the sequential chain or not: if any one of them fails, the checkout fails. Suppose each of the 7 services is available 99.9% of the time and checkout needs all of them to succeed.
- Chained availability: 0.999 raised to the 7th power (one factor per required service) = 0.99302, about 99.30%. That looks like a small drop from 99.9%, because both numbers are close to 100%.
- Over a 30-day month (43,200 minutes), that is (1 - 0.99302) x 43,200, about 301 minutes of failed checkouts, versus 0.001 x 43,200 = 43.2 minutes for a single 99.9% service. 301 / 43.2 is about 7: it is the expected downtime, not the availability percentage, that scales roughly with the number of required services.
So a design where every request synchronously depends on seven services has about seven times the expected downtime of any one of them (301 minutes a month versus 43.2), before even counting the extra latency the 6 sequential calls add on top, even though the availability percentages themselves look close (99.30% versus 99.9%). The 23-span, 6-sequential-call shape is why the request is also slow; the 7-services-required shape is why it is fragile. That is the architectural reason on-call keeps getting paged: the dependency structure multiplies failure, and no single team's service looks broken.
For deploy coupling, pull the last quarter's release records. If, for example, 31 of 50 releases needed a coordinated deploy, that 62% is the number to drive down, and the co-change data shows which service pairs to fix first.
Sequencing the remediation
The aim is to reduce risk and restore delivery speed without a big-bang rewrite:
- Measure first. Record the baseline: deploy-coupling rate, pages per week by root-cause service, median spans per key request, number of services with write access to each shared table.
- Stop the bleeding on pages. Fix the worst chatty path or break the cycle on the most-paged flow; these are local changes with fast payback.
- Stop new coupling. Add contract tests in CI, and a rule that no new service gets credentials to another service's tables. This keeps the smell from recurring while you pay down the old debt.
- Pay down the shared database table by table, starting with the tables whose migrations caused incidents.
- Report progress in delivery terms: lead time for changes (the time from a commit to it running in production) and change failure rate (the share of production changes that cause an incident), two of the DORA metrics (the software delivery measures from the DevOps Research and Assessment programme), plus the deploy-coupling rate.
Pitfalls
- Armouring instead of fixing. Timeouts and circuit breakers (a guard that stops calling a failing dependency for a while, instead of piling retries onto a call that keeps failing) limit the blast radius (how much of the system one failure can drag down) of a bad dependency but leave the dependency in place; they are not a remediation of the architecture.
- Merging everything back. Sometimes two services that always change together should become one, and that is a legitimate fix, but decide it per pair from co-change evidence, not as a reaction to pain.
- Guessing from symptoms alone. The same "cascading pages" symptom can come from chatty calls or from a cycle; the trace graph tells you which.
- Fixing everything at once. Coordinated remediation across all teams recreates the coordination problem you are trying to remove.
Explain modularity as an architecture principle and how it differs from simple componentization. Give a concrete example of module boundaries for a ride-sharing service (matching, billing, routing), and describe how you'd enforce those module boundaries at the code, CI, and runtime levels.
Sample Answer
Direct answer
Modularity means dividing a system into parts that each own one cohesive responsibility, expose a small published interface, and hide everything else, so a part can change internally without anyone else noticing. Componentization is just dividing a system into parts (libraries, packages, services) that can be built or deployed separately. You can componentize without being modular: ten separate packages that all reach into each other's internals are components, not modules. The difference is whether the boundaries are respected, and that is why modularity has to be enforced at several levels (code, CI and runtime) rather than assumed.
Modularity vs componentization
| Componentization | Modularity | |
|---|---|---|
| Question it answers | "What are the pieces?" | "What may each piece know about the others?" |
| Unit | A package, jar, library or deployable | A responsibility with an interface and hidden internals |
| Can be achieved by | Moving code into separate folders or builds | Designing interfaces and enforcing that others use only them |
| Failure mode | Pieces exist, but depend on each other's internals | Rarely accidental; it degrades when boundaries are not enforced |
The encapsulation and modularity lens
Two related ideas pull in the same direction but pay off differently:
- Encapsulation (hiding a module's internal data and logic behind its interface) mainly improves maintainability: Billing can rewrite its fare-calculation internals and nobody else changes.
- Modularity (splitting the system along cohesive boundaries) mainly aids scalability, in two senses: of teams (the matching team works without coordinating with billing) and of load (a well-bounded module can later be extracted and scaled on its own, because nothing reaches into its internals).
Encapsulation is what makes modularity real; without it, module boundaries are only folder names.
Worked example: a ride-sharing service
Three modules inside one codebase (a modular monolith), each with a public interface and private internals:
| Module | Owns | Public interface (examples) | Private (others may not touch) |
|---|---|---|---|
| Matching | Pairing riders with nearby drivers | requestMatch(riderId, pickup), emits TripMatched | Driver-location index, ranking heuristics |
| Routing | Paths and travel-time estimates | estimateEta(from, to), route(from, to) | Road-graph data, map-provider client |
| Billing | Fares, payment, receipts | quoteFare(tripSpec), handles TripCompleted | Pricing tables, payment-provider client, invoice records |
Allowed dependencies: Matching calls Routing.estimateEta to rank drivers by arrival time. Billing calls Routing.route for distance when quoting a fare. Billing listens to TripCompleted. Not allowed: Billing reading Matching's driver-location tables, or Matching computing fares itself.
Why these boundaries: each changes for a different reason (matching heuristics, map data, pricing policy) and is owned by a different team. A surge-pricing change touches only Billing.
Enforcing the boundaries at three levels
1. Code level: make the wrong import impossible to write
- Use the language's visibility rules. In Go, anything under a directory named
internal/can be imported only by code within the parent of that directory, and the compiler enforces it. In Java, the module system (amodule-info.javafile that declares which of a module's own packages it exports for others to use) exports only chosen packages; everything else is inaccessible to other modules. - Each module exposes one public package (its API); implementation classes stay package-private (a Java visibility level between public and private: visible to other classes in the same package, but invisible outside it, so nothing outside the module can import them even by accident).
2. CI level: fail the build on a boundary violation
- Add architecture tests that encode the allowed dependency rules: ArchUnit for Java, dependency-cruiser for JavaScript/TypeScript, import-linter for Python. Example rule: "classes in
billing..(the..is ArchUnit's wildcard for 'this package and every package underneath it') may depend onrouting.api..but not onmatching..". - Run them on every pull request, next to unit tests. A violation fails the build with the rule's name, so it is caught at review time, not months later.
- Each module owns its own tests and database migrations folder, so ownership is visible in the repository structure.
3. Runtime level: make shared state impossible to reach
- Separate data ownership: each module gets its own database schema and its own database user, and Billing's user has no grants (database permissions explicitly given to that user) on Matching's schema. A sneaky query fails with a permission error rather than silently working.
- If modules are later deployed as separate services: network policies (firewall-like rules, enforced by the network or the platform, stating exactly which service may open a connection to which other service) allow only the declared calls (Matching may reach Routing; Billing may not reach Matching), and service identity checks (the receiving service cryptographically verifies which service is calling, for example from a mutual-TLS certificate, instead of trusting whatever network address the request came from) reject unexpected callers. Concretely: if a bug in Billing tried to call Matching's driver-location endpoint directly, the network policy would refuse the connection before it reached Matching at all, since Billing's policy only permits outbound calls to Routing; and even if that were somehow bypassed, Matching's identity check would see a certificate identifying the caller as "billing-service", find it is not on Matching's declared list of allowed callers, and reject the call.
- Monitor the runtime dependency graph (from tracing) and alert on any edge that is not in the declared list.
Pitfalls
- Folders are not modules. Splitting into packages without enforcement gives you componentization that decays back into a tangle.
- A shared "common" module that accumulates domain types (Trip, Fare, Driver) becomes the thing every module depends on, and every change to it touches everyone.
- Premature distribution. Good modules inside one deployable give most of the maintainability benefit without network cost. Extract a module into a service only when it needs to scale or deploy on its own.
Unlock Full Question Bank
Get access to all 21 Architectural Patterns and Anti-Patterns interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.