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.
Explain the Backend-for-Frontend (BFF) pattern: how it tailors APIs per client type (mobile vs. web), reduces over-fetching, and hides internal service complexity. What deployment, testing, and team-ownership trade-offs would you weigh before adopting BFFs?
Sample Answer
Direct answer
A Backend-for-Frontend (BFF) is a small server-side API built for one specific client experience, such as the mobile app or the web app, and usually owned by the team that builds that client. Instead of the client calling many internal services and trimming the results itself, it makes one call to its BFF, which fans out to the internal services, combines the results and returns exactly the shape that screen needs. That cuts round trips and over-fetching on slow networks and hides the internal service layout from clients. The price is an extra deployable per client, extra hops, duplicated logic risk and the need for clear ownership. Adopt it when client experiences genuinely differ and each has its own team.
How it works
flowchart LR
M[Mobile app] --> MB[Mobile BFF]
W[Web app] --> WB[Web BFF]
MB --> O[Orders service]
MB --> C[Catalog service]
WB --> O
WB --> C
WB --> R[Reviews service]
- Tailoring per client. The mobile BFF returns a compact list with a thumbnail URL and price; the web BFF returns richer detail with reviews. Each BFF can also handle the client's own concerns, such as cookie sessions for web and token refresh for mobile.
- Reducing over-fetching. Over-fetching means receiving far more data than the screen uses. The BFF drops unused fields server-side, on the fast internal network, instead of over the user's mobile connection.
- Aggregation. The BFF calls several services in parallel inside the data centre and merges the results, so the client pays one network round trip instead of several.
- Hiding internal complexity. Clients see one stable API. Internal services can be split, merged or renamed, and only the BFF changes.
Worked example: one product-list screen
Assumptions (illustrative, not measured): a mobile round trip of 200 ms on a cellular network; the screen needs data from 4 services; each internal call takes 25 to 45 ms; 20 products per page; the full product object is 12 KB, while the mobile screen uses about 1.5 KB of it.
| Client calls services directly | Through a mobile BFF | |
|---|---|---|
| Round trips over the mobile network | 4 sequential calls: 4 x 200 = 800 ms | 1 call: 200 ms |
| Internal calls | none | 4 in parallel, bounded by the slowest: about 45 ms |
| Network time, approximately | 800 ms | 200 + 45 = 245 ms |
| Payload to the device | 20 x 12 KB = 240 KB | 20 x 1.5 KB = 30 KB |
The payload shrinks by a factor of 240 / 30 = 8, and the waiting time drops by more than half, which is the whole case for the pattern on mobile. If the client could already make those calls in parallel, the direct figure would be closer to 200 ms plus the slowest call, and the latency argument weakens; the payload and coupling arguments remain.
Trade-offs to weigh before adopting
Deployment
- One more service per client experience to build, monitor, scale and keep available. If the BFF is down, that client is down.
- An extra hop on every request, small inside a data centre but not zero.
- Old mobile clients never fully disappear. Users do not all update, so the mobile BFF must serve several app versions at once. Plan versioned endpoints and a support window from day one.
Testing
- Two contracts per BFF: client to BFF, and BFF to each downstream service. Consumer-driven contract tests (the BFF publishes what it relies on; each downstream service verifies it in CI) keep a service change from silently breaking a client.
- The aggregation code needs tests for partial failure: what the screen shows when the reviews service fails but orders succeeds.
Team ownership
- The pattern works best as "one experience, one BFF, one team": the mobile team owns the mobile BFF and can change screen and API in one release.
- A central team owning every BFF turns them back into a shared bottleneck.
- Logic duplicated across the web and mobile BFFs will drift. Anything that is a business rule (pricing, eligibility) belongs in a downstream service; the BFF only shapes, combines and adapts.
When to choose it, and alternatives
- Choose a BFF when two or more clients need materially different data shapes or flows and are built by different teams.
- Choose one general-purpose API when there is one client, or clients are nearly identical: separate BFFs would be duplication.
- Consider a GraphQL gateway (a single API where the client's query names exactly the fields it wants) when there are many clients with overlapping needs and you prefer self-serve field selection to per-client code. It solves over-fetching without a BFF per client, but moves query-cost control onto the server team.
Pitfalls
- Business logic creeping into the BFF, which then must be duplicated in every other BFF.
- A BFF per device type (separate iOS and Android BFFs) when the experiences are the same; split by experience, not by platform.
- BFFs calling other BFFs, which recreates chatty, coupled services at the edge.
- Mirroring internal models. A BFF that returns downstream objects unchanged gives the client a pass-through and none of the insulation.
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.
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.
Design an extensible plugin architecture for a platform where customers or internal teams can add custom business logic (for example, custom validation rules or scoring logic) without modifying the core service. Cover how plugins are structured and versioned, how you'd validate and sandbox them for safety, whether they can be hot-reloaded, how you'd enforce backward compatibility across plugin versions, and how you'd test a new plugin without risking the core service.
Sample Answer
Direct answer
I would build a microkernel (plugin) architecture: a small core that owns the data, the workflow and every side effect, plus a fixed set of named extension points (hooks such as validate_order or score_lead) where plugins are allowed to run. Plugins are pure functions over a versioned input/output contract, compiled to WebAssembly (Wasm, a portable, low-level bytecode format that runs inside its own sandboxed virtual machine with its own private block of memory, so plugin code cannot read or write anything outside that block unless the host explicitly allows it) and executed in a sandbox with hard limits on CPU, memory and host access. The core never links plugin code into its own process memory (never loads it as a native library or script sharing the core's own memory space, the way an in-process plugin would); each plugin instead gets its own separate memory and only a narrow, explicit channel back to the core. It loads plugins from a signed, versioned registry, can swap them at runtime without a restart, and only promotes a new plugin version after it has passed a conformance suite and a shadow run (running the new version on a copy of real traffic, off to the side of the request that is actually served, and comparing its output against the current version without letting it affect anything yet) against real traffic.
The key design stance: plugins compute, the core acts. A plugin returns a decision ("reject with reason X", "score = 72"); it never writes to the database or calls the network itself. That single rule is what makes safety, versioning and testing tractable.
Requirements I am designing to
- Tenants (customers) and internal teams add validation rules and scoring logic; the core team must not need to redeploy for that.
- Hot path: validation runs inline on each order submission. Budget assumption: the core's own p99 (99th percentile) latency target is 200 ms, and I give all plugins on one request a combined budget of 20 ms.
- A buggy or malicious plugin must not crash the core, read another tenant's data, or exfiltrate data over the network (secretly send it out to somewhere the plugin's author controls).
- Hundreds of tenants, each with a handful of plugins, so plugin count is in the low thousands, not millions.
Architecture
flowchart LR
Dev[Plugin author] --> CI[Plugin pipeline: build, sign, conformance tests]
CI --> Reg[(Plugin registry: artifact + manifest + version)]
Reg --> Loader[Core: plugin loader]
Req[Order request] --> Core[Core service]
Core --> Host[Plugin host: Wasm sandbox]
Loader --> Host
Host --> Core
Core --> DB[(Core database)]
1. How a plugin is structured
Each plugin is an artifact plus a manifest:
| Manifest field | Example | Why it exists |
|---|---|---|
name, version | acme-credit-check, 2.3.1 | Semantic versioning (MAJOR.MINOR.PATCH) for the plugin's own releases |
api_version | validation/v2 | Which version of the core's extension contract it targets |
hooks | ["validate_order"] | Which extension points it implements |
capabilities | ["read:order", "config:thresholds"] | Everything it asks the host for; nothing else is granted |
limits | timeout_ms: 5, memory_mb: 32 | Requested ceilings, capped by platform maximums |
owner, signature | tenant id, signing key id | Accountability and tamper detection |
The contract is a small SPI (service provider interface: the interface the core publishes for plugins to implement), defined in an interface definition language rather than in one programming language. For Wasm, that is a WIT file (WebAssembly Interface Types, the interface language of the Wasm Component Model: a standard way for Wasm modules to describe and exchange typed interfaces, so a module written in one language can be called correctly from a host, or from another module, written in a different one), which lets authors write plugins in Rust, Go, JavaScript or Python and still meet one contract. Input is a read-only snapshot the core prepares (the order, the tenant's config), output is a typed decision.
2. Versioning
Two version numbers matter, and conflating them is the common mistake:
- Contract version (
validation/v1,validation/v2) is owned by the core. Within a major version, only additive changes are allowed: new optional input fields, new optional output fields. Removing or retyping a field means a new major version. - Plugin version (
2.3.1) is owned by the author. The registry is immutable:2.3.1can never be overwritten, only superseded, so every decision in the audit log can be traced to exact bytes.
Each tenant pins a plugin version per hook (acme-credit-check@2.3.1). Upgrading is an explicit promotion, never "latest".
3. Validation and sandboxing
Validation happens before a plugin can run anywhere near production:
- Signature check: the artifact is signed by the pipeline; the loader refuses unsigned or re-signed bytes.
- Static checks: the Wasm module only imports functions the host actually offers for its declared capabilities. An import the manifest did not declare fails the upload.
- Conformance suite: the core team publishes contract tests per hook: golden inputs (a fixed set of sample inputs with known-correct expected outputs, which every plugin version is checked against) and required behaviours such as never throws on an empty cart, always returns a reason with a rejection, handles unknown optional fields. Every plugin version must pass them in CI.
At runtime, the sandbox enforces what the manifest promised:
- Memory: each instance gets a fixed linear-memory cap (32 MB here): linear memory is Wasm's name for a module's own private, contiguous block of memory, the one described above, and a Wasm module can only ever address bytes inside its own block. So it cannot read the core's heap (the pool of memory the core process itself uses to hold its own data) even by accident.
- CPU: the runtime meters execution. Wasmtime, for example, offers fuel consumption (a deterministic instruction budget) and epoch interruption (a periodic deadline check); either stops an infinite loop at the time budget.
- Host access: no filesystem, network or clock unless the manifest's capabilities grant a specific host function. Tenant isolation comes from the core only ever passing that tenant's own snapshot in.
- Failure policy per hook, decided up front: a validation hook that times out or traps fails closed (the order is held for review, because silently accepting an invalid order is worse), a scoring hook fails to a default (a neutral score) and emits an alert. A plugin that fails more than a threshold (say 5% of calls in 5 minutes) is auto-disabled for that tenant and its owner is paged.
4. Hot reload
Yes, and it is cheap because plugins are stateless and sandboxed:
- The loader watches the registry for promotion events.
- It fetches and compiles the new version in the background.
- It atomically swaps the tenant's pointer from the old compiled module to the new one. Requests already running keep the old instance; new requests get the new one.
- The old module is dropped once its in-flight count reaches zero.
Rollback is the same swap in reverse, so it takes seconds and needs no deploy. What I would not hot-reload is the contract itself: a new api_version ships with a core release.
5. Backward compatibility across plugin versions
- The core supports the current and previous contract major version (
v2andv1) at the same time, using an adapter that translates av2input down tov1shape for old plugins. - Every contract change runs the entire registry's current pinned plugins against the new core in CI. If a change to the core breaks any pinned plugin, the core change fails, not the plugin.
- Deprecation has a published window (for example two quarters), a dashboard of which tenants are still on
v1, and direct outreach before removal.
6. Testing a new plugin without risking the core
Progressive exposure, each stage automated:
| Stage | What runs | Risk to production |
|---|---|---|
| Local SDK | Author runs the plugin against a local host binary with sample inputs | None |
| Conformance CI | Contract tests plus fuzzed inputs (automatically generated random or malformed inputs meant to find edge cases a human author would not think to write by hand) | None |
| Replay | New version runs over a recorded day of that tenant's (anonymised) inputs; decisions are diffed against the current version | None |
| Shadow | New version runs on a copy of live inputs alongside the pinned version, off the request path (after the response is sent); its output is logged but ignored | Extra compute only; no user-visible latency |
| Canary (a canary release: rolling the new version out to a small, real slice of traffic before trusting it with all of it) | New version's decisions take effect for 5% of that tenant's requests | Limited to one tenant, one slice |
| Full | Promoted | Rollback is one pointer swap |
Worked example: does the latency budget hold?
Assume a tenant has 3 validation plugins on validate_order, run sequentially because later rules may depend on earlier outcomes, with a per-plugin timeout of 5 ms.
- Worst case with every plugin hitting its timeout: 3 × 5 ms = 15 ms, inside the 20 ms plugin budget.
- A 4th plugin lands exactly on the line: 4 × 5 ms = 20 ms, equal to the budget, not over it. I treat the budget as inclusive (a request may use up to and including 20 ms of plugin time), so a 4th plugin is technically allowed, but it leaves zero margin, so in practice I would cap tenants at 3 sequential plugins and require anything beyond that to run in parallel instead.
- A 5th plugin makes that explicit: 5 × 5 ms = 25 ms, which exceeds 20 ms even before any margin. The platform either rejects the configuration or requires the tenant to mark independent rules (ones that do not depend on each other's output) as parallel, in which case the worst case is max(5 ms) plus scheduling overhead, the extra time to dispatch several plugin calls at once and wait for the slowest one to finish, typically well under a millisecond, rather than the sum of every plugin's timeout.
That calculation is why the manifest carries limits and why the platform, not the author, caps them: the budget is a property of the whole request, not of one plugin.
Trade-offs and pitfalls
- Letting plugins perform side effects. The moment a plugin can write to the database or call an external API, you need transactions across plugin code, retries, and data-access policy per plugin. Keep plugins pure and have the core act on their decisions.
- In-process plugins "for speed". Loading tenant code as a native library or script inside the core process means one bad plugin can crash or read everything. Worth it only for internal code written and reviewed by the core team.
- An extension point per request. Every hook is a contract you must keep backward compatible forever. Start with a few well-chosen hooks and add more when there is real demand.
- "Latest" pinning. Auto-upgrading plugins turns every author release into an unreviewed production change for every tenant.
- Plugins that need heavy compute or long-running work (calling an ML model, minutes of processing) do not fit the inline Wasm model. Those belong out of process, behind an asynchronous job interface, which is a different extension point with different latency expectations.
What would change the design: if plugins were only ever written by the core company's own teams, I would drop Wasm and load them in-process behind the same SPI, trading isolation for easier debugging.
Unlock Full Question Bank
Get access to all 20 Architectural Patterns and Anti-Patterns interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.