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.
A customer needs significant customization, but your product is built around a single core codebase shared by every customer. Propose an architecture and delivery approach that balances customizability with maintainability: consider feature flags, plugin or extension models, configuration schemas, and release management.
Sample Answer
Direct answer
Keep one codebase and one release train for every customer (a release train is a fixed release schedule that ships whatever is ready on time, instead of a separate release per customer) and never fork for a customer. Offer customization as a ladder, cheapest rung first: schema-validated configuration, then feature flags and entitlements, then extension points through a small published plugin or webhook API (a webhook is a URL the customer gives you that your system calls, with an event's data, when something happens). Only when a request cannot be met on those rungs does it become either a product feature (if other customers want it too) or a paid, out-of-process integration that the customer's code runs against your stable API. Release management then treats each customer's configuration and extensions as test fixtures that every release candidate (a build that is a candidate for shipping, pending final checks) must pass.
The customization ladder
| Rung | What it is | Good for | Cost and risk |
|---|---|---|---|
| 1. Configuration | Per-customer settings stored as data, checked against a configuration schema (a formal definition of allowed keys, types and ranges, such as JSON Schema) | Thresholds, labels, workflows chosen from built-in options, field visibility | Cheap; the schema stops invalid settings before they reach production |
| 2. Feature flags and entitlements | Runtime switches that turn code paths on or off per customer. Release flags hide unfinished work and are removed later; entitlement flags represent what a customer has bought and are permanent | Gradual rollout, paid tiers, early access | Each flag doubles the possible states; stale flags become dead code (code paths that can no longer run but are still sitting in the codebase) |
| 3. Extension points | A plugin (microkernel) model (microkernel: the core itself does almost nothing and delegates real work to swappable plugins): a small stable core with named hooks (beforeInvoiceApproval, onOrderCreated) that extensions implement through a published interface. Prefer out-of-process extensions (webhooks, or customer code run in a sandbox, an isolated environment that limits what that code can reach or break) to in-process plugins | Customer-specific logic you cannot predict: calling their ERP (enterprise resource planning) system, custom validation | A public contract you must version and support; timeouts and failures of customer code |
| 4. Product feature | Generalize the request into the product for everyone | A request 3 or more customers would use | Normal product cost, no per-customer burden |
| Never: a fork | A customer-specific branch of the code | Nothing long-term | Every release must be merged and tested once per fork |
Worked example: a custom invoice-approval flow
A customer wants invoices above 50,000 USD to need two approvers, and wants their own budget system consulted before approval.
- Configuration covers the first half. The product already supports approval rules, so add
approval.threshold_amountandapproval.required_approversto the schema (integer, minimum 1, maximum 5). The customer's config sets 50,000 and 2. No code is specific to this customer. - An extension point covers the second half. Add a
beforeInvoiceApprovalhook that calls a customer-registered webhook with the invoice summary and expects allow or deny. Define its contract: a 3-second timeout, a signed request, and a documented default when the webhook fails (hold the invoice for manual review, never auto-approve). The customer's integration code runs on their side, not in your core. - Productize the hook. Other customers can now register the same hook, so the work becomes a product feature rather than a one-off.
Why not forks, and why flags need discipline: the arithmetic
- Forks. With 5 customer forks and 24 releases a year, each release must be merged and regression-tested 5 extra times: 5 x 24 = 120 extra merge-and-test cycles a year, on top of the 24 for the main line. The work grows with customers times releases, which is why forked products stall.
- Flags. 12 independent on/off flags allow 2 to the power 12 = 4,096 combinations; you cannot test them all. So test the combinations that actually exist: each real customer's configuration becomes a named profile, and a mandatory expiry date on release flags keeps the count from growing without bound.
Release management
- Single trunk (everyone commits to one shared mainline, with no long-lived customer branches), one version for everyone, with customizations carried as data (config, flags) and as extensions against a versioned API.
- Versioned extension API. Semantic versioning (version numbers written MAJOR.MINOR.PATCH, where a MAJOR bump means a breaking change) for the hook contracts, a published deprecation window (for example two major releases), and a compatibility test suite extension authors can run.
- Customer profiles in CI. Each release candidate runs the regression suite (the automated tests that check old behaviour still works) against every significant customer's configuration and their registered extension contracts (with the webhooks stubbed, meaning replaced with a fake that returns their documented response instead of calling the customer's real endpoint).
- Progressive rollout in rings (releasing to successively larger groups instead of everyone at once): internal tenants (your own company's teams, using the product first as tenants of the same shared system customers will later use), then early-adopter customers, then everyone, with flags as the kill switch (a flag you can flip to turn the feature back off instantly, without a deploy).
- Customization governance. Every custom request is reviewed against the ladder: can it be config, a flag or a hook? Anything needing core changes for one customer needs explicit product sign-off. Retire flags on a schedule.
Trade-offs and pitfalls
- Configuration as a programming language. When config grows conditionals and loops, you have built an untested scripting language; move that logic to a proper extension point.
- In-process plugins with full access. Customer code in your process can crash it, leak other customers' data or block upgrades. Prefer out-of-process extensions unless latency truly requires in-process, and then use a narrow, sandboxed interface.
- Leaky extension contracts. A hook that passes internal database entities makes your schema a public API; pass a documented, versioned model.
- Golden hammer (reaching for one familiar pattern regardless of whether it fits the problem) in either direction. Building a plugin framework before a second customer needs it is premature; saying yes with an
if customer == "acme"branch is the start of a fork. Build the extension point when the second similar request arrives. - What would flip the approach: a single, very large customer paying for a dedicated deployment might justify a separate instance (still the same code, with its own configuration and release timing), but not a code fork.
Describe encapsulation in the context of service APIs and data models. Explain how exposing internal data structures (for example, database-schema details) in service responses can lead to production issues, and how stronger encapsulation would have prevented them. Include one example of an enforcement mechanism.
Sample Answer
Direct answer
Encapsulation for a service means clients see a deliberate, stable contract (the fields and behaviour the service promises) and never the internal representation behind it (table names, column names, database IDs, internal status codes, ORM objects). When a service serialises its database rows straight into API responses, every client silently couples to the schema, so an ordinary internal change such as a column rename or a table split becomes a breaking change in production, and fields that were never meant to leave the service leak out. The fix is an explicit response model that the service owns and maps to, with an automated check that stops internal types from reaching the wire.
How schema leakage causes production issues
Suppose an orders endpoint returns the ORM (object-relational mapping) entity directly:
{
"ord_id": 88213,
"cust_fk": 4411,
"status_cd": 3,
"tot_amt_cents": 12999,
"deleted_at": null,
"internal_fraud_score": 0.82,
"customer": { "id": 4411, "password_hash": "..." }
}
Each of those fields is a future incident:
- Renames break clients. A developer renames
tot_amt_centstototal_centsin a routine migration. The web app is redeployed the same day, but installed mobile app versions keep readingtot_amt_centsand show a blank or zero total until every user updates, which can take weeks. - Internal codes become a public contract. Clients hard-code
status_cd == 3to mean "shipped". The team later inserts a new status "packed" as 3 and renumbers the rest, and every client now shows the wrong state. - Sensitive data leaks.
internal_fraud_scoreand a lazily loadedcustomer.password_hash(the ORM fetches a related row, here the customer, only when code actually touches it rather than upfront, so merely serialising an order can silently trigger the query that pulls it in) were never meant to leave the service, but serialising the whole entity sends them anyway. - Write-side over-posting. If the same entity is also accepted as input, a client can send
"status_cd": 3or another privileged field and the framework will happily bind it (often called mass assignment). - Performance surprises. Serialising an entity walks its relationships (turning the object into JSON touches every related object, and each one that is lazily loaded triggers a fresh database query the first time it is touched, rather than being fetched upfront), so adding a new relationship to the model can suddenly trigger dozens of extra queries or a huge payload for every response.
- Physical IDs leak. Exposing sequential database keys lets anyone enumerate records and makes it painful to re-key or merge databases later.
The pattern behind all six: the service gave away the right to change its own internals.
What stronger encapsulation looks like
The same endpoint returning a contract the service owns:
{
"id": "ord_7Kq2Lm",
"customer_id": "cus_9Qa1",
"status": "shipped",
"total": { "amount": "129.99", "currency": "USD" }
}
- Stable external IDs (opaque strings) instead of database keys.
- Named enum strings ("shipped") instead of internal numeric codes.
- Only fields that clients need, chosen on purpose; nothing sensitive is reachable.
- A mapping function between the internal entity and this response model. When the column is renamed, one line in the mapper changes and the response is identical.
Applied to each earlier failure: the rename touches only the mapper (1), the enum stays "shipped" whatever the database stores (2), the fraud score and password hash are not on the response type so they cannot be serialised (3), requests bind to a separate input model that has no status field (4), the mapper reads only what it needs (5), and external IDs hide the physical key (6).
An enforcement mechanism
My choice is an architecture test in CI that forbids API handlers from returning or accepting persistence types. For example, in a Java service an ArchUnit rule states that classes in the ..api.. package may not depend on classes in the ..persistence.entity.. package; in Python, an import-linter contract does the same between the API module and the models module. A developer who takes the shortcut gets a red build, not a code-review debate.
Two complementary checks make it stronger:
- Contract checking: the response schema is written in an OpenAPI document (a machine-readable API description), responses are validated against it in tests, and a breaking-change diff tool runs on every pull request so removing or renaming a public field is flagged.
- Consumer-driven contract tests: each client publishes the fields it actually uses, and the provider's build fails if a change would break one of them.
Trade-offs and pitfalls
- Mapping boilerplate is the real cost. It is worth it on any API with external or independently deployed clients; for a throwaway internal admin tool it may not be.
- Mirror DTOs (data-transfer objects that copy every column one-for-one) give the look of encapsulation with none of the benefit. The response model should be designed from what clients need.
- Leaking through errors: raw database error messages ("duplicate key violates constraint orders_pkey") expose the schema just as effectively. Map errors to stable error codes too.
- Leaking through query parameters: letting clients sort or filter by arbitrary column names (
?sort=tot_amt_cents) couples them to the schema through the request instead of the response.
What's the difference between loose and tight coupling between services, and why does it matter for how independently teams can ship? Name a few concrete techniques you'd use to loosen coupling in an existing tightly-coupled system, and describe how you'd actually measure or surface coupling levels across a codebase or service map today.
Sample Answer
Direct answer
Two services are tightly coupled when one cannot change, deploy or even stay up without the other: it depends on the other's internal details (field names, database tables, timing, availability). They are loosely coupled when each depends only on a small, stable, published contract and can tolerate the other being slow, down, or on a different version. It matters for shipping because coupling decides the unit of release: if Team A's change forces a change or a coordinated deploy in Team B's service, the two teams move at the speed of their slowest shared calendar. To loosen coupling I use stable versioned contracts, events instead of synchronous calls where the caller does not need an immediate answer, and each service owning its own data. To measure it I combine three views: the static dependency graph, the runtime call graph from traces, and change history.
The kinds of coupling (it is not one thing)
| Kind | Tight looks like | Loose looks like |
|---|---|---|
| Contract | Consumer reads the provider's internal data shape or table | Consumer depends on a documented, versioned API or event schema |
| Temporal (runtime) | Caller blocks until callee responds; callee down means caller down | Caller publishes an event or enqueues work and moves on |
| Deployment | Releases must happen together or in order | Either side ships alone; old and new versions coexist |
| Data | Two services write the same table | Each service owns its data; others get copies via events or ask through the API |
| Knowledge | Consumer duplicates the provider's business rules | Consumer asks for the decision, not the rule |
A useful mental model: coupling is the number of things the other side could change that would break you. Loosening coupling shrinks that list.
Techniques to loosen an existing tightly coupled system
- Put an explicit, versioned contract in front of every dependency. Replace direct table reads with an API or event, version it, and make changes additive only (add fields, never rename or remove in place).
- Consumer-driven contract tests. Each consumer declares the fields and behaviours it relies on; the provider runs those checks in its own build, so it learns before deploying whether it breaks anyone. This is what lets deploys become independent.
- Move from synchronous calls to events where no immediate answer is needed. The publisher announces a fact ("OrderPlaced") and does not know or care who listens.
- Give each service its own data, with local read copies. If Shipping needs a customer's address, it keeps its own copy updated from
CustomerAddressChangedevents instead of calling Customer on every shipment. - Anti-corruption layer (a translation layer at the boundary): when you must integrate with a messy legacy model, translate it into your own model at the edge so its quirks do not spread into your code.
- Tolerant reader. Consumers ignore unknown fields and do not depend on field order, so providers can add fields freely.
Choosing between REST, event-driven and async messaging: a worked example
Scenario: an e-commerce platform where Checkout currently calls Loyalty, Email, Analytics and Inventory synchronously during order placement.
| Interaction | Does the caller need the answer now? | Choice | Why |
|---|---|---|---|
| Checkout needs to know stock is reserved before confirming | Yes, the user waits for the result | Synchronous request/response (REST, or gRPC, a binary remote-procedure-call framework) | The answer changes what the user sees; a queue would just make the user wait on a queue |
| Loyalty points, Email receipt, Analytics | No, they react to a completed order | Event-driven publish/subscribe (Checkout publishes OrderPlaced to a topic, a named channel in the message broker that any number of subscribers can listen to without the publisher knowing who or how many they are; each subscribes) | Checkout no longer knows these consumers exist; adding a fifth consumer needs zero Checkout changes |
| Generate a PDF invoice, 5 to 30 seconds of work | No, but it is a command to one specific worker | Async point-to-point messaging (a work queue) | Exactly one worker should do it, with retries and a dead-letter queue (DLQ, where messages that keep failing are parked for inspection) |
Before: order placement had 4 synchronous downstream dependencies, so an Email outage failed checkouts. After: 1 synchronous dependency (Inventory), and Email being down only delays receipts. The distinction that drives the choice is "does the caller need the result to continue?" plus "is this a fact for anyone, or a command for one worker?".
Measuring coupling across a codebase or service map
View 1: static dependency graph (what the code declares)
Build the graph of which service or module depends on which, from build files, imports or client libraries. For each node compute:
- Ca (afferent coupling): how many others depend on it.
- Ce (efferent coupling): how many it depends on.
- Instability I = Ce / (Ca + Ce), from 0 (everyone depends on it, it depends on nothing) to 1 (it depends on everything, nothing depends on it).
Example: Checkout depends on 6 services and 2 depend on it, so I = 6 / (2 + 6) = 0.75, close to 1 (fully unstable). That is fine for a top-level orchestrator (a service like Checkout that coordinates a business process by calling out to several others, rather than being called deep inside someone else's process): nothing else in the system depends on it in any deep way (Ca = 2 is low), so a change to Checkout has nowhere further outward to ripple; being "unstable" just means it is free to change because it sits at the edge of the graph, not the centre.
The warning sign is a shared service everyone depends on (high Ca) that also has high Ce, and it is worth working a number for: suppose a shared Pricing service has Ca = 8 (eight other services call it) and Ce = 5 (it itself calls five other services or data sources, for tax rates, currency conversion and so on). Its instability is I = 5 / (8 + 5) ≈ 0.38, a middling number that looks unremarkable if you only glance at I. The two raw counts are the real story: high Ca means eight other services need to change, or at least be retested, whenever Pricing's contract changes (hard to change safely), and high Ce means Pricing itself is exposed to five other services' changes rippling into it (likely to change often). A healthy shared service instead aims for high Ca with low Ce, an I closer to 0.1-0.2: many dependents, but few dependencies of its own that could knock it over. Also flag cycles in this graph; every cycle is a set of services that can no longer be released in any safe order.
View 2: runtime call graph (what actually happens)
Distributed tracing, instrumentation that tags every call belonging to one request with a shared id so the calls across every service can be reassembled afterward into one end-to-end record (for example OpenTelemetry, an open standard for doing this), records every call a request makes. From traces, build the live service map and track per endpoint:
- Fan-out: downstream calls per inbound request.
- Synchronous depth: longest chain of blocking calls.
This catches coupling that static analysis misses, such as calls built from configuration, or a service calling another 40 times in a loop.
View 3: change history (how the code actually evolves)
From version control, compute temporal coupling: how often two services change in the same ticket or release. High temporal coupling with no declared dependency is the most interesting finding, because it means a hidden dependency (a shared schema, a duplicated rule).
Put all three on one dashboard. Each alone misleads: the static graph shows declared dependencies, traces show runtime behaviour, history shows what actually slows teams down.
Trade-offs and pitfalls
- Loose coupling has a price. Events give you eventual consistency (subscribers see the change a little later), harder debugging across asynchronous hops, and message schemas that still need versioning. Use them where decoupling is worth that, not everywhere.
- Async is not automatically loose. An event that carries the publisher's full internal entity couples every subscriber to that entity's shape.
- Over-abstracting. A generic "universal integration layer" in front of everything becomes its own tightly coupled god component: one component that has absorbed so much shared responsibility that everything else ends up coupled through it.
- Cohesion is the other half. Low coupling between services only helps if each service is cohesive (its parts belong together). Splitting a cohesive unit apart raises coupling, however many events you add.
Describe a typical three-tier (multi-tier) layered web architecture: presentation/UI, application/business logic, and persistence/data. For each tier, name its responsibilities, then trace how a single request flows through the system, from the client through ingress, load balancing, and the application tier down to the data tier and back. What are the trade-offs of this architecture (scalability, deployment complexity, testability) compared to a simpler two-tier design or a flatter, event-driven one?
Sample Answer
Direct answer
A three-tier architecture splits a web application into three independently deployed parts: the presentation tier (what runs in or is sent to the user's browser or app), the application tier (the servers that apply business rules) and the data tier (the databases and stores that keep state). Each tier talks only to its neighbour, so the browser never touches the database directly. You pay for an extra network hop and more moving parts, and in exchange you get a stateless middle tier you can scale by adding servers, one place to enforce security and rules, and parts you can test and deploy separately.
A useful distinction up front: a tier is a physical deployment unit (separate machines or containers), while a layer is a logical grouping of code inside one program. Three-tier is about tiers.
The three tiers and what each owns
| Tier | Responsibilities | Typical technology | Should NOT do |
|---|---|---|---|
| Presentation | Render screens, capture input, client-side validation for fast feedback, call the API | React or server-rendered HTML, mobile app, static assets on a CDN (content delivery network: servers near users that cache files) | Hold business rules or database credentials |
| Application | Authenticate and authorize, validate input authoritatively, apply business rules, coordinate transactions, call other services, shape responses | Stateless API servers (Java, Go, Node, Python) behind a load balancer | Keep user session state in local memory (breaks horizontal scaling) |
| Data | Store and retrieve durable state, enforce integrity (keys, constraints), run indexed queries, replicate and back up | PostgreSQL or MySQL, plus a cache such as Redis and object storage for files | Encode business workflows in stored procedures that nobody can test |
Tracing one request: GET /orders/123
- Client. The browser already loaded the presentation code from the CDN. The user opens "My orders", and the JavaScript sends
GET /api/orders/123over HTTPS with a session token. - Ingress and load balancing. DNS resolves the API hostname to a load balancer (or, in Kubernetes (a container-orchestration system: software that runs and manages many server instances across a fleet of machines for you, restarting failed ones and scheduling new ones), an ingress controller: the component that admits outside traffic into the cluster). It terminates TLS (decrypts HTTPS), checks which application instances are passing health checks (a periodic ping each instance must answer, so the load balancer stops sending traffic to one that has stopped responding), and forwards the request to one of them.
- Application tier. The chosen instance validates the token, checks the rule "a customer may only read their own orders", and asks its data-access code for order 123. It may check a cache first.
- Data tier. A connection is borrowed from the instance's connection pool (a set of already-open database connections the instance keeps ready, so a request reuses one instead of paying the cost, tens of milliseconds, of opening a fresh connection to the database each time), an indexed
SELECTruns against the orders table, and rows come back. - Back up the chain. The application maps rows to a JSON response (dropping internal columns), returns 200, the load balancer relays it, and the browser renders the page.
sequenceDiagram
participant B as Browser
participant LB as Load balancer
participant App as App server
participant DB as Database
B->>LB: GET /api/orders/123 over HTTPS
LB->>App: forward to a healthy instance
App->>App: check token and ownership rule
App->>DB: SELECT order 123
DB-->>App: rows
App-->>LB: 200 JSON
LB-->>B: 200 JSON
Because step 3 keeps no per-user state in memory, any instance can serve the next request from the same user. That property is what lets the middle tier scale out.
Worked example: where the bottleneck moves
Suppose peak load is 1,200 requests per second (RPS) and a load test shows one application instance sustains about 150 RPS.
- Instances needed: 1,200 / 150 = 8. Run 10 so that losing one or two still leaves capacity (25% headroom).
- Each instance keeps a database connection pool of 20 connections: 10 x 20 = 200 connections.
- PostgreSQL's
max_connectionsdefault is typically 100 (the documentation notes it can be lower if kernel settings do not support 100).
So the design that scales the application tier by adding boxes will exhaust the data tier at peak, exactly when the autoscaler (the system that automatically adds or removes application instances based on load) adds instances. Fixes: shrink each pool (10 x 8 = 80 connections), or put a connection pooler such as PgBouncer between the tiers: a lightweight service that holds a smaller, fixed number of real connections to Postgres and multiplexes many application-side requests through them. PgBouncer's own default is session pooling, which hands one real connection to an application connection for its whole session and would not shrink the connection count here; the setting this design actually needs is transaction pooling mode, which hands a connection out per transaction and takes it back the instant that transaction commits or rolls back, then reuses it for the next request. PgBouncer also offers a statement pooling mode that returns the connection after every individual query, but that mode explicitly disallows transactions spanning multiple statements, which would break a multi-step operation like a funds transfer, so transaction mode, not the default and not statement mode, is the setting to reach for. That lets the same 200 application-side connections be served through, say, 50 real database connections instead of colliding with the 100-connection ceiling. The general lesson is that the application tier scales horizontally cheaply and the data tier does not, so in a three-tier system the bottleneck usually migrates to the database.
Trade-offs versus two-tier and event-driven designs
A two-tier design has the client talk straight to the database (a desktop app with a database driver, or a small server-rendered app where UI code and SQL live in one process). An event-driven design has components publish events ("OrderPlaced") to a broker such as Kafka (a system dedicated to durably queueing and delivering these events to every interested component, so the publisher does not need to know who is listening or whether they are online right now), and other components react asynchronously instead of being called directly.
| Dimension | Two-tier | Three-tier | Event-driven |
|---|---|---|---|
| Scalability | Every client holds database connections; the database takes all load | Stateless middle tier scales out; the database remains the limit | Consumers scale independently; the broker absorbs spikes |
| Deployment complexity | Lowest: one app plus a database, but rolling out a desktop client means updating every install | Moderate: load balancer, app fleet, database, each with its own deploy | Highest: broker, topics, consumers, schema versioning for events |
| Testability | Rules mixed with UI or SQL are hard to test in isolation | Business rules testable in the application tier without a UI | Each consumer testable alone, but end-to-end flows are hard to test and debug |
| Security | Database credentials sit on or near the client | Database reachable only from the app tier | Must also secure the broker and every topic |
| Time to market | Fastest for small internal tools | Reasonable default for most web products | Slowest to start; pays off when work can happen later |
| Failure behaviour | Database down means everything is down | A slow database slows every request synchronously | A slow consumer builds a backlog but the user-facing request still succeeds; data is eventually consistent (other parts catch up after a delay) |
Recommendation. Use three-tier as the default for a customer-facing web product. Use two-tier only for small internal tools with a handful of trusted users. Add event-driven pieces for work the user does not need to wait for (emails, search indexing, analytics), which gives a hybrid: synchronous three-tier for the request path, events for side effects. What would flip this: if most work is naturally asynchronous (ingesting sensor data, processing uploads), an event-driven core is the better starting point.
Pitfalls that separate strong answers
- Stateful application servers. Sessions kept in instance memory force "sticky" routing (the load balancer must keep sending one user to the same instance every time, because that instance is the only one holding their session in memory), and users get logged out when an instance dies. Keep sessions in a token or a shared store.
- A pass-through middle tier. If the application tier only forwards requests to SQL, you paid for a hop and got nothing; the rules have leaked into the client or into stored procedures (business logic written and run inside the database itself, rather than in the application tier).
- Confusing tiers with layers. Splitting every code layer onto its own network hop adds latency without adding isolation you need.
- Forgetting that tiers fail together. In a synchronous chain, a slow data tier makes the whole request slow; the architecture does not isolate that by itself.
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.
Unlock Full Question Bank
Get access to all 19 Architectural Patterns and Anti-Patterns interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.