AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals

Choosing Modular Monoliths or Microservices for AI Applications

Question 20 of 47 · Updated

On this page

Start with well-defined domain modules and extract an independently deployed service only when its own scaling, hardware, release cadence, security, failure-isolation or ownership requirements justify the additional distributed-system complexity. For many early AI products, a modular business application plus independently operated inference and background workers provides a better balance than either putting every workload in one process or turning every model, prompt, tool and database table into its own microservice.

Original curriculum question: How do you choose between modular monoliths and microservices for an AI application?

Module 01 — Architecture fundamentals | ASD-007. ASD-001 chooses the computational architecture, ASD-003 sizes capacity, ASD-004 chooses execution contracts and ASD-005 chooses sourcing and operating responsibility. This lesson focuses on deployment topology, ownership and consistency boundaries after those decisions have been made. The existing MLOps lessons on managed versus self-hosted platforms and twelve-factor ML applications are prerequisites, not substitutes. The pending Python lessons about monoliths, migration and service communication cover general software mechanics; AI-agent framework runtime lessons cover their respective SDKs. Here the distinctive objective is the topology of a whole AI product across business state, retrieval, CPU/GPU execution, model and feature releases, background jobs and independent domain teams. ASD-006's prediction/authority separation applies to both topologies. ASD-008 will cover the wider transition from prototype to production; ASD-018 will develop cross-system compensation; ASD-023 coordinated releases of model-related dependencies; ASD-083 versioned service event contracts; ASD-200 enterprise consolidation. The extraction plan here illustrates the topology decision rather than replacing those lessons.

All example traffic, measurements, replica rates, costs, deadlines and team sizes are fictional planning assumptions. No real distributed service, accelerator cluster, infrastructure cost or end-to-end performance was benchmarked. Only the executable Python contract example was tested locally.

1. Separate modularity from distribution#

A monolith is generally an application whose core components are deployed together as one logical release unit. It can run many replicas, have an external database and use queues or worker processes. It need not be a single huge file, and one repository is not what makes something a monolith.

A modular monolith organizes business capabilities behind explicit internal contracts. Modules encapsulate rules and data access, have disciplined dependency directions, and can be tested independently while sharing a deployment unit. It combines relatively cheap local calls and transactions with design boundaries that may later become service boundaries.

A microservice is an independently deployable service that owns a cohesive capability and its contracts. Independence matters more than size. A microservice can have substantial internal modules and several replicas. Multiple services may share a repository or deployment platform; separate repositories do not automatically produce loose coupling. A set of services that must always deploy together, share undocumented tables, and fail as one is a distributed monolith.

Distinguish at least four kinds of boundary:

BoundaryQuestionDoes it require a network service?
DomainWho owns a business concept and its rules?No
CodeWhich interfaces and dependencies are permitted?No
Deployment/resourceWhat must release, restart or scale independently?Sometimes
Trust/dataWho may read or change authoritative state?Not necessarily, but enforcement must be real

The topology should emerge from these boundaries, not from a prescribed service count. A CPU API and a GPU model server can be two deployments without making every domain capability an independently operated microservice. A modular product core can call a managed model API, private inference service and queue-based workers while remaining a modular monolith at its business boundary.

2. Begin with bounded contexts and business invariants#

A bounded context is an explicit boundary within which domain terms and models have a consistent meaning. In a research workspace, a document revision in the document domain is different from an embedding/index revision in retrieval. A generated artifact is different from a draft in the editor. A model invocation is different from a successful user task and from a billable account event.

Map the business actions before mapping components. Identify the authoritative state, required invariants, upstream inputs and downstream consumers. Ask which operations must be atomic and which can tolerate propagation lag.

Capability/contextOwnsDoes not own
Identity and accessMembership, permissions and scoped authorizationModel predictions or search rankings
DocumentsCanonical document IDs, revisions and access metadataModel weights and derived index layout
RetrievalDerived indexing, query contracts and evidence referencesAuthority to change a document's access rules
AI orchestrationTask planning, invocation and validationUnilateral authority to commit business actions
InferenceApproved model execution and typed outputOrders, billing or document access policy
Jobs and artifactsDurable job lifecycle, output manifests and artifact identityPermission to expose restricted source content
Usage/billingLogical usage events and approved charge rulesRaw model claims as proof of a committed outcome

This is an illustrative decomposition, not a recommendation for seven services. Begin with modules inside the product core for contexts that need tight coordination or share transactional invariants. Isolate inference execution when its hardware and lifecycle warrant it. Use durable jobs or external search only where the requirements justify those boundaries.

Information hiding matters: a module should hide design decisions likely to change, such as index format or model runtime. Other modules depend on stable operations rather than importing private implementation details or writing each other's tables. A bounded context is not automatically one service; several related modules can share a release, and a large context may need multiple deployment units.

3. Three viable topologies#

A. Modular monolith with colocated model#

Loading diagram…

Good for a small team, a compact CPU model or a carefully managed small local accelerator workload, modest traffic, uncertain product shape and closely coordinated changes. Internal calls can be straightforward; many business invariants fit a local transaction. A change to one module may still require application deployment and regression testing. If the model consumes substantial accelerator memory or starts slowly, colocating it with every API replica can become wasteful. Do not assume a queue is required merely because the diagram includes optional background work.

B. Modular business core plus specialized AI runtimes#

Loading diagram…

The application core retains coordinated business rules and user-facing contracts. The GPU runtime can have an independent scale target and compatible model releases, while workers can run lengthy jobs without occupying interactive application resources. Retrieval may itself be a module or managed service; it does not have to be extracted into a new domain service just because a vector database exists. This topology is often a strong starting candidate for AI applications with heterogeneous resource requirements.

C. Independently owned domain services#

Loading diagram…

Consider when domains have stable contracts, separate teams and materially independent scaling, reliability, compliance or release requirements. Each service must own its data semantics and operational obligations. In this illustration the event log carries change notifications, not an unrestricted copy of every private record. Consumers need purpose-limited access. Cross-service operations require explicit deadlines, idempotency, version compatibility and failure handling. Do not choose this topology purely because the product uses an LLM, retrieval and agents.

4. Compare architecture choices against evidence#

CriterionModular monolithSpecialized runtime hybridDomain microservices
ReleaseShared product releaseProduct release plus selected independent runtimesIndependent domain and runtime releases where contracts allow
Resource scalingApplication replicas may scale togetherCPU and accelerators can scale separatelyEach independently constrained pool can scale
TransactionsLocal business operations can be atomicLocal business transactions remain; remote AI effects need contractsCross-owner operations require coordination
LatencyCheap local calls; shared contention possibleNetwork hop to model/runtimeAdditional service hops, serialization and tail risk
IsolationProcess and release boundaries may be sharedHeavy workload/failure pools can be isolatedMore potential isolation, but dependency graph can propagate failures
Data accessSimpler access within one store, disciplined module ownership neededBusiness store separate from derived/runtime stateExplicit service-owned APIs and events
SecurityFewer network trust boundaries; coarse process privilege riskIsolate model/runtime credentials and processingFiner-grained identities possible, more boundaries to manage
OperationsFewer release units and on-call surfacesModerate increaseMore discovery, contracts, observability, on-call and migrations
Team fitCohesive small team or rapidly changing scopeCore team plus specialized platform capabilityStable autonomous teams with operational ownership

These are tendencies, not guarantees. A modular monolith can be replicated across zones; a microservice can be unreplicated and unreliable. A service boundary provides isolation only if resources, credentials, deployment and dependency policies actually enforce it. Shared infrastructure can defeat nominal separation.

Make a shortlist of feasible candidates. Exclude designs that fail mandatory data isolation, resource placement, availability or latency requirements. Compare validated alternatives on total cost, ease of change, operability and the expected next stage of product growth. Never use a weighted architecture score to offset a mandatory security or correctness violation.

5. AI-specific pressure: CPUs, GPUs and model lifecycles#

Conventional request handlers often consume modest CPU and memory; an LLM inference runtime may reserve a large accelerator allocation, maintain KV cache, batch sequences and require long warm-up. A training or embedding job can consume substantial resources for minutes or hours. Their scaling signals differ.

An independently deployed GPU service can pool warm replicas, support a validated request mix, constrain memory use and provide an admission boundary. The CPU application can deploy product changes without unnecessarily reloading model weights. It can also keep ordinary requests independent of inference when the product permits. Use an approved fallback if model capacity is unavailable.

Separate deployment is not a universal performance win. A tiny tabular model with negligible memory overhead may be much faster and cheaper in-process. Moving it across a network introduces serialization, timeout handling, service discovery, authentication and additional failure modes. Benchmark both against the same useful task contract.

Consider several additional AI boundaries:

  • Training versus serving: Training requires dataset snapshots, experimental state, checkpointing and accelerator jobs. Serving needs approved artifacts and predictable admission. Even when sharing a platform, these workloads may need separate resource pools.
  • Interactive versus offline inference: Long context requests or batch embeddings can starve low-latency traffic. Separate worker pools, priority/admission controls and tested scheduling may be needed even within one inference service.
  • Retrieval versus generation: Retrieval may scale with corpus size, memory, search QPS and index refresh; generation scales with token distributions, model memory and decode capacity. Their data and release dependencies remain compatible through a contract.
  • Model lifecycle versus application lifecycle: Approve compatible model, calibrator, feature schema, prompt template, output contract and index versions. Independent deployment does not mean arbitrary version mixing is safe.

Use the actual deployment unit: a model replica might need multiple GPUs and topology-aware placement. A shared accelerator scheduler or Kubernetes device plugin exposes resources but does not guarantee that workloads meet latency, fairness or memory objectives. Validate real placement, isolation, startup and failure behavior. Separate containers alone do not prevent CPU, storage, network or GPU contention.

6. Worked scenario: independent scaling of heterogeneous workloads#

A fictional product receives 120 peak logical requests/s. Fifteen percent need a local accelerator-backed model, producing 18 offered inference requests/s, assuming one model attempt per AI request and no additional fan-out. The remaining 102 requests/s use only business logic or data lookup.

Assume benchmark inputs that have not actually been measured:

Deployment unitSustainable offered capacityPlanning factorPlanned capacity
Application CPU replica40 logical requests/s0.7530 requests/s
One-GPU inference replica12 inference requests/s0.759 requests/s

Both stages must retain planned capacity after losing one replica. With homogeneous replicas, fixed traffic mix and one-spare policy from ASD-003:

Application units = ceil(120 / 30) + 1 = 5
GPU units         = ceil(18 / 9) + 1  = 3

Suppose a colocated design must attach one GPU to every application replica, and the colocated units can sustain both component envelopes simultaneously under representative mix. Five combined replicas would be required by the API peak even though only three GPU replicas are needed by inference. With four surviving combined replicas, API planned capacity is 120 requests/s and inference planned capacity is 36/s.

A separated design uses five CPU replicas and three GPU replicas. After losing one CPU replica and one GPU replica in their respective pools, surviving planned capacity is 120 logical requests/s and 18 inference requests/s. This only establishes the arithmetic envelope. It does not protect against a node or zone failure removing several replicas, nor guarantee the distribution of inference arrivals across the remaining GPUs. The benchmark must include shared gateway, retrieval, networking and queuing overhead, and actual topology and fault domains must be tested.

Fictional incremental hourly resource costs:

ResourceColocated deploymentSeparated deployment
CPU application portion at $0.12/unit-hour5 × $0.12 = $0.605 × $0.12 = $0.60
GPU runtime portion at $1.80/unit-hour5 × $1.80 = $9.003 × $1.80 = $5.40
Subtotal$9.60/hour$6.00/hour

Under the invented additive billing assumption, the difference is $3.60/hour or $2,592 in a 720-hour month. This is replica-resource savings only. It excludes the additional service's ingress, networking, security, telemetry, extra engineering and operations, and potential differences in actual host CPU resources or pricing. The separated design may need additional host overhead or an additional standby pool; confirm those before claiming savings.

Suppose additional recurring service-operation cost is $1,500/month and implementation cost is $8,000. The simple net recurring saving becomes $1,092/month and arithmetic payback is about 7.33 months of operation after the extraction. These values are hypothetical and undiscounted. At a higher AI share, the advantage may shrink or reverse. At 40% AI share, offered inference is 48/s and the same envelope requires ceil(48/9)+1=7 GPU replicas. The colocated design also needs at least seven combined units if its joint capacity assumption holds, rather than five. Re-evaluate using measured mixes, actual cost curves and separate reliability requirements. ASD-005 provides the full sourcing economics; here the point is how topology changes resource coupling.

7. Communication contracts and latency#

Choose a communication mode according to the product contract rather than make every internal interaction HTTP. Local module calls are appropriate inside the business core. Remote request-response suits bounded inference with a deadline. Durable commands suit asynchronous jobs. Events describe committed domain facts and allow interested consumers to update derived state. Token/progress streaming is a delivery mechanism, not a new domain boundary.

Avoid fine-grained remote calls that recreate object-oriented getter/setter interactions over the network. A single domain operation should usually carry the complete approved input and return a typed result. Define the request ID, tenant/purpose, payload/schema version, feature and model compatibility, deadline, result semantics and safe error states. Avoid sending an entire customer record merely because the local implementation could access it.

A network call must address timeouts, cancellation, admission, retries and ambiguous outcomes. Propagate the remaining deadline rather than granting every hop a full new timeout. Bound retries to prevent cascading load. An unavailable model result must not become an arbitrary confident prediction. For write operations, use stable logical intent keys and authoritative receipt lookup. HTTP or gRPC alone does not guarantee business idempotency.

For an illustrative 250 ms interactive budget, suppose the application reserves 35 ms for validation/authorization, 35 ms for feature access, 130 ms for inference, 20 ms for response processing and 30 ms contingency. A remote boundary must fit serialization, transport and queuing into this allocation or cause an approved redesign. Those are planning allocations, not measured percentiles; adding component p95s does not establish end-to-end p95. Measure complete request distributions under burst load and dependency failures.

Two mandatory independent serial components with availability 99.9% each would have a simplified combined availability of 0.999 × 0.999 = 99.8001%. Independence is not a safe default for real shared infrastructure, and alternative paths change the result. Model the failure graph and measure the actual task SLO, including degraded modes. A remote dependency that is optional on most requests need not make all tasks unavailable when it fails.

8. Data ownership is not database-per-table#

A modular monolith may use a single relational database, while granting each module ownership of its tables, schema migrations and operations. Cross-module reads should use explicitly approved interfaces or governed projections rather than arbitrary undocumented dependencies. Cross-module transactions can be appropriate when an invariant truly spans the shared boundary.

For independently deployed services, prefer one owner for authoritative state. Other services request operations from that owner or consume versioned events/projections. Physically distinct servers are not always necessary; separate schemas or accounts can establish ownership if access controls, migrations and operational limits are real. A single shared database with unrestricted writers defeats independence even when there are many containers.

In AI applications, derived embeddings, features, caches and prediction histories are not authoritative business state. A retrieval index may reflect a previous document revision. Store source identifiers, revision and as-of time, and check current access at the appropriate boundary. Source deletion or permission revocation must propagate according to an approved contract; a stale vector match cannot grant access. An embedding service should not be able to change a user's membership or document policy.

For analytics or cross-context reads, a materialized read model or governed warehouse can combine published events without forcing synchronous joins across every service. It has an explicit freshness/completeness contract. Do not use an eventually consistent projection to decide a hard business invariant that requires current authoritative state.

Consider the document service and retrieval index: the document owner commits revision 12 and its event in the same transaction. The indexer receives the event, fetches approved data, embeds it using an approved version and publishes a versioned index entry. Duplicate events must be safe. An older revision 11 arriving later must not overwrite revision 12. If indexing is delayed, expose the permitted freshness state; if access is revoked, enforce current authorization even while the derived index is catching up. Data ownership is about authority, not merely where bytes are stored.

9. Distributed transactions and business invariants#

One of the largest changes when extracting a service is losing the assumption that a business operation can update all involved tables within one local ACID transaction. Network failure can occur after an external service commits but before a caller sees its response. A distributed database product may provide transactions within a documented scope, but arbitrary HTTP services and model calls do not participate automatically.

Keep strongly coupled invariants together when practical. For example, reservation quantity and remaining stock are best enforced by the inventory owner, as in ASD-006. Avoid extracting a pricing rule and transaction check into independently writable services if a single atomic invariant becomes unnecessarily difficult.

When a business operation must span owners, choose a coordination contract:

PatternPurposeLimitation
Local transactionCommit state and related records within one storeDoes not include remote side effects
Transactional outboxAtomically record business change and publication intentRelay may publish more than once
Consumer inbox/deduplicationTrack processed event IDs alongside a local effectDeduplication must cover the actual retention/replay window
SagaCoordinate steps and authorized compensationsIntermediate states may be visible; compensation is not rollback of all effects
ReconciliationResolve uncertain or divergent states against authoritative receiptsRequires explicit ownership and correction policy

A report task might reserve quota, generate an artifact and record completion usage. If quota reservation and job creation share a local database, one transaction can commit them together. If billing becomes a separate owner, define a pending reservation and acknowledgment contract. Only record successful business completion after the required state transition. Do not infer from generated text that an artifact was published or a charge occurred. Use explicit receipts, idempotent commands and recovery procedures.

Loading diagram…

The ordering of progress recording and consumer acknowledgment is not a globally atomic transaction. The relay can retry publishing an already delivered event after a crash; the consumer must tolerate repeats. An index service may use a durable work record plus a versioned conditional index write rather than a literal single transaction across separate databases. For external sinks without a transactional guarantee, verify the actual conditional-write and reconciliation capabilities. Sagas and cross-system compensation receive detailed coverage in ASD-018.

10. Deployment independence without version chaos#

A real independently deployed component can change its implementation without breaking compatible consumers or requiring a simultaneous application rollout. However, AI contracts include semantic compatibility beyond field names.

For example, a model can continue returning a floating-point score in [0,1] while its meaning changes from probability of defect in the next day to probability of any defect in the next month. A consumer's threshold would no longer mean the same thing. Changing an embedding dimension, tokenizer, index metric or preprocessing convention can also break retrieval even when an API returns the same JSON field.

Use an approved compatibility matrix:

Artifact or contractCompatibility check
API schemaAccepted request/response versions, required fields and behavior
Feature schemaField semantics, units, transformations and missingness
Model releasePrediction target, horizon, class encoding, artifact digest
Calibration/policyApproved model-calibrator-policy combination
Embedding/indexModel version, dimension, normalization, distance metric and index generation
Prompt/tool contractAllowed capabilities, output schema, safety and semantic expectations
EventsVersioned domain semantics, ordering and consumer compatibility

Use expand/contract changes where appropriate: introduce a new field or endpoint while supporting existing consumers, validate both, migrate traffic, and retire the old contract after evidence and approval. Schema backward compatibility is not proof that task quality remains acceptable. Run representative model evaluations and consumer contract tests, including failure and rollback scenarios.

A prompt-only change may alter how a model invokes a tool or cites evidence; it must go through the relevant release gate even if no application binary changed. Independently deployed services may still require coordinated promotion of compatible model and feature artifacts. Make the coordination explicit, not an accidental synchronized release of every unrelated service.

11. Practical implementation: preserve a port during inference extraction#

The following Python example demonstrates an internal inference port and a serialized adapter that could later be backed by a real service. The business decision module owns a toy review threshold and validates response correlation and release compatibility. Both adapters use the same synthetic predictor, which echoes a valid numeric feature as the score. It is not a trained or calibrated model.

The "remote" adapter serializes a typed request to JSON, calls an injected transport function, then decodes the response. In the tests the transport is an in-process function. The purpose is to establish the consumer contract before introducing a network dependency, not to pretend that a network service is already running.

PYTHON
from dataclasses import dataclass, asdict, replace from math import isfinite import json import unittest @dataclass(frozen=True) class Request: request_id: str tenant: str feature: float release: str = 'model-v1' @dataclass(frozen=True) class Prediction: request_id: str release: str score: float def predict(req): # A deterministic fixture, not a trained model. return Prediction(req.request_id, req.release, req.feature) def local(req): return predict(req) def wire_handler(body): req = Request(**json.loads(body)) return json.dumps(asdict(predict(req)), allow_nan=False) def remote_adapter(transport): def invoke(req): body = json.dumps(asdict(req), allow_nan=False) return Prediction(**json.loads(transport(body))) return invoke def evaluate(req, port): # The authenticated tenant must come from trusted caller context. if (not req.request_id or not req.tenant or req.release != 'model-v1' or type(req.feature) not in (int, float) or not isfinite(req.feature) or not 0 <= req.feature <= 1): return 'INVALID_REQUEST' try: result = port(req) if (not isinstance(result, Prediction) or result.request_id != req.request_id or result.release != req.release or type(result.score) not in (int, float) or not isfinite(result.score) or not 0 <= result.score <= 1): return 'UNAVAILABLE' except (TimeoutError, ValueError, TypeError, KeyError, OSError): return 'UNAVAILABLE' return 'REVIEW' if result.score >= .7 else 'NORMAL' class ContractTests(unittest.TestCase): def setUp(self): self.req = Request('r1', 'tenant-a', .8) self.remote = remote_adapter(wire_handler) def test_local(self): self.assertEqual(evaluate(self.req, local), 'REVIEW') def test_serialized(self): self.assertEqual(evaluate(self.req, self.remote), 'REVIEW') def test_parity(self): for score in (0, .69, .7, 1): req = replace(self.req, feature=score) self.assertEqual(evaluate(req, local), evaluate(req, self.remote)) def test_threshold(self): self.assertEqual(evaluate(replace(self.req, feature=.7), local), 'REVIEW') def test_normal(self): self.assertEqual(evaluate(replace(self.req, feature=.69), local), 'NORMAL') def test_invalid_input(self): for score in (float('nan'), -1, 2, True): self.assertEqual(evaluate(replace(self.req, feature=score), local), 'INVALID_REQUEST') def test_wrong_release(self): self.assertEqual(evaluate(replace(self.req, release='v2'), local), 'INVALID_REQUEST') def test_missing_tenant(self): self.assertEqual(evaluate(replace(self.req, tenant=''), local), 'INVALID_REQUEST') def test_wrong_id(self): self.assertEqual(evaluate(self.req, lambda r: Prediction('wrong', r.release, .8)), 'UNAVAILABLE') def test_wrong_result_release(self): self.assertEqual(evaluate(self.req, lambda r: Prediction(r.request_id, 'v2', .8)), 'UNAVAILABLE') def test_invalid_result(self): for score in (float('inf'), -.1, 1.1, True): self.assertEqual(evaluate(self.req, lambda r: Prediction(r.request_id, r.release, score)), 'UNAVAILABLE') def test_timeout(self): def timeout(_): raise TimeoutError() self.assertEqual(evaluate(self.req, remote_adapter(timeout)), 'UNAVAILABLE') def test_malformed_json(self): self.assertEqual(evaluate(self.req, remote_adapter(lambda _: '{')), 'UNAVAILABLE') def test_missing_field(self): self.assertEqual(evaluate(self.req, remote_adapter(lambda _: '{}')), 'UNAVAILABLE') if __name__ == '__main__': unittest.main()

Observed execution with Python 3.13.5:

..............
Ran 14 tests
OK

The 14 unittest methods exercise local and serialized invocation, parity at four numeric boundaries, the review threshold, a normal outcome, invalid scores, unknown request release, missing tenant, wrong response correlation, incompatible response version, invalid returned scores, injected timeout, malformed JSON and missing response fields. Some tests contain several assertions. The consumer maps these expected remote failures to UNAVAILABLE rather than falsely declaring NORMAL.

A real deployment must authenticate and authorize the tenant at both boundaries; the example assumes trusted caller context and merely checks that tenant is nonempty. It does not establish a secure request schema for arbitrary Python objects, bound JSON size, validate every identifier type, cryptographically authenticate a response or prove the model release served by the transport. A malicious transport could echo an expected release and invent a score. Use authenticated service identities, trusted release manifests, schema validation, integrity and version checks appropriate to the risk. The toy predictor/handler accepts only the test contract and is not exposed as a server.

The injected TimeoutError tests failure handling, not actual deadline propagation or wall-clock behavior. A real transport must configure deadlines, cancellation, retry limits, request size and concurrency; a real service must enforce admission and resource controls. Unexpected programming errors should be observed, not silently treated as legitimate model outcomes. Contract equality of the toy predictor is not evidence of equivalent real-model behavior across hardware, runtime or preprocessing versions. Validate those separately.

Extraction should preserve the domain-level port: existing consumer code can use local or service adapter based on approved configuration. The service adapter becomes a boundary where data minimization, identity and deadline controls can be enforced. A rollback is safe only when the local adapter remains compatible, authorized and sufficiently provisioned. This example performs no side effect and does not test network, multiprocess or cluster behavior.

12. Reliability and observability#

Distribution introduces partial failure: one service is down, slow, overloaded or serving incompatible artifacts while others are healthy. A monolith can fail through process crashes or shared resource pressure; microservices can reduce the affected scope if they are genuinely isolated and callers degrade safely. A service can also amplify an outage through retry storms and cascading queues.

Measure the user-visible task across boundaries. Propagate request and trace IDs through asynchronous handoffs, maintain parent/child or linked spans as appropriate, and separate logical task IDs from retry attempts and job IDs. Record model/feature/index/policy versions, result category and safe timing metadata. Protect sensitive prompts, documents, credentials and personal identifiers; telemetry is not a free unrestricted copy of source data.

SignalWhat it helps establish
End-to-end valid response rate and deadlineConsumer experience, not merely component uptime
Per-hop latency and queue timeWhich dependency contributes to tail delay
Inference goodput, input/output token work and memoryCapacity of the actual model workload
Index lag and source version mismatchDerived state freshness
Contract and version errorsIndependent release compatibility
Retry rate and overload rejectionPotential amplification and contention
Outbox age, replay and reconciliation backlogCross-owner propagation health
Authorization denials and incident evidenceEnforcement behavior and unexpected attempts

Distributed tracing adds value when following actual cross-service dependencies. It does not replace quality evaluation, audit trails or authoritative receipts. Instrument the modular monolith's internal modules too: measured local cost and dependency data provide evidence for deciding which module to extract. Sample and retain traces according to policy, preserving useful failure visibility without excessive exposure or cost.

Use bulkheads such as bounded thread pools, connection pools, queue partitions and accelerator resource pools where justified. A circuit breaker can stop sending doomed calls to a failing dependency, but its fallback must preserve required semantics. A health check for a GPU service should distinguish process liveness, readiness of the approved model and workload-level availability. Recovery includes warm-up and capacity readiness, not just restarting a container.

13. Security across process and trust boundaries#

Do not assume a microservice is trusted because it runs on an internal network. Authenticate workload identity, authorize the requested operation and tenant/purpose scope at the resource owner, and minimize data passed to inference. Use encrypted transport where required, bounded egress, secret management, reviewed images and model artifacts, and explicit network access. For user-delegated tasks, distinguish the calling workload's identity from the end user's authorization.

In a monolith, internal modules share a process and may share credentials. Code boundaries are useful but not a security boundary against arbitrary code execution within the same privilege context. If an AI tool executes untrusted code, processes restricted data requiring isolation, or has access to privileged systems, use a meaningful sandbox or separate trust boundary. Splitting a service without reducing its credentials or permitted network access may not improve security.

In the hybrid topology, the model runtime receives only the features or context needed for prediction. It need not have direct write access to the business database. An authorized business service validates output and executes permitted operations as in ASD-006. The inference server's model-generated response is untrusted input. Retrieval must enforce authorized source access before sending context to the model. A downstream redactor cannot retract data already disclosed upstream.

For microservices, ensure service-to-service contracts cannot bypass tenant scope, and propagate current authority correctly across queues and background jobs. Do not trust an event payload's self-declared role or tenant. Validate its producer and scope; recheck authority for protected reads and effects. Review logs, backups, derived indexes and cache keys across all boundaries. A new service may increase the attack surface and operational patching obligations even if it enables stronger isolation.

14. Team structure and operational cost#

Team boundaries should support, not dictate, domain boundaries. A small cross-functional team working on rapidly changing product requirements often benefits from one deployable core and shared tooling. It can maintain coherent internal interfaces without inventing operational independence before the domain is understood.

When several teams have stable responsibilities and independent change rates, independently deployed services can reduce release coordination. Each service needs an accountable owner for code, data, runtime configuration, quality/SLOs, security, incident response, dependencies, schema evolution and decommissioning. Do not create a service whose operational responsibility falls between teams. An AI platform team may own an inference runtime while product teams own business semantics and their own task-level quality. Centralizing model serving is not centralizing every business decision.

The marginal cost of a service includes more than compute. Consider CI/CD, deployment configurations, credentials, discovery, network transport, tracing, dashboards, version and schema migrations, integration tests, runbooks, on-call, recovery and team coordination. Shared platform tooling can reduce but not eliminate this overhead. Even an idle service may require monitoring, patching and support. An in-process module still needs design discipline and testing but usually avoids some network operations.

Compare the same functional and quality requirements over a realistic time horizon. If a separate inference service materially reduces GPU duplication, it may justify its operating cost. If splitting a small frequently changing business module adds months of coordination with no measured isolation or release benefit, keep it local. ASD-005 covers ownership and managed-service choices, which are separate from deployment topology.

15. Practical extraction strategy#

Avoid a large rewrite just to adopt microservices. Extract a bounded capability when evidence identifies a specific problem.

  1. Record the trigger: for example model warm-up slows API releases, GPU replicas scale differently, or a distinct team needs independent model updates. Quantify the cost or reliability impact.
  2. Stabilize the internal module port, dependency direction, data ownership, behavior and approved model/version contract. Remove direct cross-module table writes and hidden global state.
  3. Implement a service adapter with secure communication, timeouts, admission, typed errors, observability and contract tests. Create a separately deployable runtime with realistic readiness and rollback.
  4. Test with authorized synthetic or replayed inputs. For read-only inference, shadow comparisons can detect semantic differences without exposing results to users. Account for extra compute. Do not duplicate real side effects in shadow traffic.
  5. Move a limited approved traffic cohort, compare useful quality, tail latency, failure handling and resource/cost evidence. Keep the old route available only within its authorized and tested capacity.
  6. Migrate remaining traffic once gates pass. Reconcile state, retire the old implementation and remove obsolete dependencies and credentials. If data ownership is changing, explicitly transfer write authority at a coherent cutover boundary; avoid indefinite dual writers.
Loading diagram…

The strangler-style approach moves a well-defined slice rather than rewriting the whole product at once. For a stateless predictor extraction, no new business database may be necessary. Extracting a document or billing owner is more complex because authoritative data, permissions, events and transactions must migrate. The next ASD-008 lesson focuses on wider prototype-to-production modernization; this lesson is not a full migration playbook.

16. A second scenario: document-assistance product evolution#

Imagine four engineers launch a small document assistant. Core requirements are authenticated document uploads, retrieval-grounded answers, a durable report job and current access enforcement. A modular application with an external approved LLM endpoint, a managed database and a separate background worker may be enough. It can maintain modules for document ownership, authorization, orchestration and job state without deploying each as a service.

Later, the product introduces a self-operated model that consumes substantial accelerator memory. The API scales with interactive traffic, while GPU capacity depends on long context and decoding. Model releases also require lengthy warm-up. An independent inference runtime is justified if benchmarks and costs confirm benefit; preserve business transaction authority in the core.

Later still, several departments require dedicated retrieval capabilities, and a team owns indexing, document revision compatibility and evidence freshness. Extract a retrieval service if independent ownership and load justify it. Keep source authorization and index freshness explicit. Introduce a versioned event contract for committed document changes. Do not create a document service solely because the index has a different database.

If reports now run on expensive, long-lived jobs, isolate the job execution resource pool and preserve the durable job lifecycle. A service for artifacts may be justified by separate retention, access and distribution requirements, but a shared artifact module may remain adequate. Observe real bottlenecks and ownership conflicts. The target is a small set of cohesive independently useful services, not the largest possible service inventory.

17. Verification and acceptance checklist#

Before approving a topology change, verify:

AreaAcceptance evidence
Domain independenceModule/service owns clear concepts, invariants and published interface
Resource isolationRepresentative CPU/GPU load, readiness, headroom and noisy-neighbor tests
Functional parityLocal/remote contract and end-to-end task evaluation
Semantic compatibilityApproved model, feature, prompt, policy and index release combinations
ConsistencyDuplicate events, stale writes, partial commits and reconciliation tests
Failure handlingTimeouts, cancellation, dependency outages, retries and fallback drills
SecurityAuthenticated identities, resource/tenant authorization, privilege and data flow review
ObservabilityTraceable task failures, version provenance and named alert owners
EconomicsBilled resource and operational cost per useful completed task
Deployment independenceConsumer compatibility during upgrade/rollback, readiness and on-call ownership

A distributed implementation does not pass because its health endpoints respond. A monolith does not pass because it is simple. Test under the required workload, data and failure conditions, and verify the user's full task. Use requirements from ASD-002, capacity assumptions from ASD-003 and versioned business-policy rules from ASD-006.

18. Common architectural mistakes#

MistakeBetter decision
One service per model, prompt or database tableChoose cohesive domain/resource boundaries
Equate repository count with deployment independenceAssess runtime, release and contract independence
Shared tables with unrestricted cross-service writersEstablish authoritative data ownership and interfaces
Move a tiny CPU model remotely without evidenceCompare local versus remote latency and operational cost
Load large GPU weights into every CPU API replicaTest separate model deployment and pooling
Treat event transport as an atomic business transactionUse scoped local transactions, idempotency and reconciliation
Independently release incompatible model and feature versionsMaintain semantic compatibility and promotion gates
Give all services the same privileged credentialsEnforce least privilege and resource-level authority
Assume every failure is isolated by a containerTest shared dependencies and failure domains
Ignore on-call burden and contract testingAssign operational owners and include costs
Rewrite everything to achieve a fashionable architectureExtract a measured bottleneck through stable ports

19. Interview-ready answer#

I would first identify bounded contexts, authoritative data, business invariants and the team's ability to operate the system. I would design a modular core with explicit interfaces and keep strongly coupled transactions local where appropriate. Then I would assess which AI workloads have genuinely independent resource, deployment, security or failure-isolation needs. A large GPU runtime, background jobs and a memory-intensive retrieval service may justify separate deployments even if the business application remains a modular monolith.

I would compare candidate topologies using measured traffic, model memory, latency, availability, release compatibility and full operational cost. If extracting a service, I would define ownership, versioned API and event contracts, authorization, deadlines, idempotency and recovery semantics. I would keep business decisions and effects outside the inference runtime, handle cross-owner state through explicit coordination, and instrument the whole user task.

Finally I would extract incrementally through a stable port, test equivalence and failures, canary the new route, verify resource savings and retire old dependencies only when the gates pass. The best architecture is the simplest topology that satisfies real domain, resource and operational requirements, not a fixed preference for monoliths or microservices.

References and research transparency#

The authorized offline research exception was applied. The references identify established architecture literature, primary systems research and official technical documentation. Live contents, link availability and the current Supabase changelog could not be verified. Five standard triple-backtick Mermaid diagrams were reviewed structurally; parser execution and live frontend rendering were not tested. The exact Python code was locally executed using Python 3.13.5 and all 14 unittest methods passed. The serialized adapter uses an in-process mock transport, not a real network deployment, and no GPU, cluster, security, concurrency, distributed transaction or load benchmark was performed. All worked financial and capacity inputs are illustrative.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython