Weighing Monoliths, Modular Designs, and Microservices
Medium · System Design · Software Engineer · Technical Screen
Prompt
Evaluate the trade-offs among three backend structures: an unstructured single-binary monolith, a microservice fleet, and a modular design. Walk through both directions of architectural evolution: how to extract targeted services out of a growing monolith, and how to consolidate an over-split set of microservices back into cleaner, coarser modules.
No fixed engineering headcount, request volume, deployment setup, or production incident is given upfront. State concrete assumptions—and clarify what concrete pain point drives the redesign (such as release lockstep, uneven compute or memory scaling, tangled code ownership, blast-radius control, or slow developer iteration). Because "modular" can describe either a single-deployable modular monolith or well-bounded internal modules inside a small group of services, define both shapes clearly rather than assuming that adding network services automatically improves scale or maintainability.
Scope & Expectations
- Clarify the motivating bottleneck, organizational scale, domain and data ownership lines, and which operations require atomic transactions before proposing an architecture.
- Quantify latency, availability, consistency, and operational overhead across plain monoliths, modular monoliths, and network-separated services.
- Detail an incremental, reversible migration roadmap in each direction where legacy and replacement paths run side by side without halting feature delivery.
- Show how introducing or removing a network hop alters partial-failure semantics and how core business invariants stay protected throughout the transition.
Step-by-step walkthrough
Clarify the motivating pain and the four architectural shapes
Architecture is a tool for solving a specific bottleneck, never a trophy for having more boxes on a diagram. Before recommending any split or merge, ask which concrete problem hurts today, because each pain has a different cheapest fix:
- Deployment coupling (one team's bug blocks or rolls back seven teams' release): usually solved by strict module boundaries, feature flags, and fast automated pipelines—not necessarily 50 network services.
- Scaling bottlenecks: splitting only helps when one workload has an asymmetric resource profile (such as a 20 GB in-memory search index or GPU inference). A stateless monolith already scales horizontally by adding identical server instances behind a load balancer.
- Unclear ownership and slow builds: solved by compile-time module boundaries, per-module code owners, and incremental test runners with zero network latency added.
- Fault isolation: separate processes isolate memory leaks or CPU spikes, unless services call each other in a synchronous chain where one slow service stalls every caller upstream.
Because "modular architecture" can mean two things, let's define all four shapes clearly:
- Plain monolith: One deployable binary and one shared database where any file can import any other file and query any table by convention alone.
- Modular monolith: Still one deployable binary, but partitioned into strict domain modules. Each module exposes a narrow public interface, build tools fail CI if Module A imports Module B's internals, and each module owns its own database schema.
- Microservices: Many independently deployed processes, each owning its private database and communicating strictly over the network via RPC (remote procedure calls) or asynchronous events.
- Coarse domain services (internal domain modules inside each service): A small number of domain-aligned services (roughly one or two per team), where each service is structured internally as a modular monolith. This is the natural destination both when extracting selectively from a monolith and when consolidating an over-fragmented microservice fleet.
Because baseline scale and failure modes are open, let's anchor our analysis with two concrete scenarios and measurable exit criteria:
- Scenario A (Monolith -> Selective Services): An automotive service-scheduling platform (customers book maintenance at dealerships, check service-bay capacity, reserve parts, pay a deposit, and receive SMS reminders).
600klines of code,1PostgreSQL database (350tables),7teams (50engineers),1,500req/s peak across24instances,55-minute CI, weekly release train.- Measured pain:
9-day median lead time,25%release rollback rate (rolling back all 7 teams together), and an availability-search index consuming20 GBof RAM on every one of the24monolith instances (480 GBtotal). - Target goals: Lead time
<= 2days, rollback rate<= 10%, independent daily deploys, RAM cut by> 50%, while keeping bookingp99 <= 800 msand99.9%availability.
- Measured pain:
- Scenario B (Over-Fragmented Microservices -> Clearer Modules): The same product split prematurely into
60microservices across4teams (25engineers). One booking traverses7synchronous network hops,3services write to the same database tables, and70%of releases require coordinated multi-service deploy checklists.- Target goals: Booking
p99from1,800 msdown to< 800 ms, coordinated deploys< 15%, and lower weekly on-call pages.
- Target goals: Booking
Quantify the trade-offs with concrete numbers
Dimension Plain Monolith Modular Monolith Microservices --------------------- ------------------- ------------------------ ---------------------------------- Deployment unit 1 whole app 1 whole app 1 service per deploy Cross-module call In-process (~50 ns) In-process (~50 ns) Network (~1-3 ms median + tails) Multi-module ACID tx Yes (1 DB commit) Yes (1 DB commit) No (requires sagas + outbox) Boundary enforcement Human convention Compiler / CI linter Process + network wall Resource scaling Whole app copies Whole app copies Per service (CPU vs RAM vs GPU) Refactoring boundary Minutes in IDE Minutes in IDE Weeks (versioned API + data move) Fixed ops overhead 1 CI, 1 runtime 1 CI, 1 runtime N pipelines, alerts, certs, SDKsFour back-of-the-envelope calculations show why "more services" often makes reliability and latency worse:
- Availability multiplies downward across synchronous chains: Suppose each service achieves
99.9%uptime (~8.8hours downtime/year). If a booking requires7independent synchronous hops, end-to-end availability drops to0.999^7 = 99.30%(~61hours downtime/year!). Cutting7hops to2raises availability back to0.999^2 = 99.80%. - Tail latency amplifies with every hop: If each of
7services independently has a1%chance of experiencing a garbage-collection or network hiccup slower than its p99, then1 - 0.99^7 = 6.8%of user bookings hit at least one p99 stall. - Where service extraction genuinely saves money (Scenario A): Duplicating a
20 GBread-only availability index across24monolith instances burns480 GBof RAM. Extracting just Availability Search into6dedicated memory-optimized replicas uses120 GB—saving360 GBimmediately. - Fixed per-service engineering tax (Scenario B): Every deployable service needs CI/CD maintenance, dependency/OS patching, dashboards, runbooks, and contract upgrades. At a conservative
0.15engineer-years per service per year,60services consume9of Scenario B's25engineers (36%of total headcount) before writing a single product feature.
- Availability multiplies downward across synchronous chains: Suppose each service achieves
Discover domain, data, and transaction boundaries from evidence
Never draw service lines from guesswork or technical layers (like a
"Validation Service"or"Database Service"). Instead, map bounded contexts—cohesive business areas such as Booking, Parts Inventory, Payments, and Search that each own a distinct set of rules—using four objective inputs:- Table-access matrix (
R= reads,W= writes) extracted from SQL logs or ORM code. - Transaction map: Which tables must commit atomically inside one ACID transaction (a database unit of work that succeeds all-together or rolls back completely)?
- Git co-change history: Files modified together in 60%+ of pull requests belong inside the same module boundary.
- Team ownership (Conway's law): Because software boundaries mirror team communication lines, avoid splitting one 5-person team's daily workflow across four repositories.
Here is Scenario A's table-access matrix before cleanup:
Database Table Booking Parts Payments Notifications Dealer-Admin Search ------------------ -------- ------ --------- -------------- ------------- ------ appointments R / W R R R R / W R <- 2 writers! bay_capacity R / W R / W R <- 2 writers! parts_inventory R R / W R part_reservations R / W R / W <- shared tx! payments R / W R customers R R R R / WReading this matrix tells us the exact migration order:
- Eliminate multi-writer tables first: Every table gets one owning module.
part_reservationsbelongs toParts;Bookingstops writing that table directly and callsPartsApiinstead. - Spot shared transactions:
Bookingupdatesappointments,bay_capacity, andpart_reservationsin one ACID transaction. KeepingBookingandPartsas sibling modules in the same core deployable preserves that exact transaction for free. - Extract read-only / async edges first:
Searchhas zero writes (Ronly), andNotificationsonly reacts after a booking commits.
Every module exposes a narrow, transport-agnostic contract so callers do not care whether the implementation runs in-process today or over RPC next year:
from dataclasses import dataclass @dataclass class PartReservationResult: reservation_id: str status: str # "reserved" or "unavailable" class PartsApi: """Public boundary for the Parts module (backed in-process or via RPC client).""" def reserve_parts( self, appointment_id: str, dealer_id: str, part_numbers: list[str], ) -> PartReservationResult: raise NotImplementedError def release_parts(self, appointment_id: str) -> None: raise NotImplementedError- Table-access matrix (
Target architecture for Scenario A (modular core + targeted extraction)
To hit Scenario A's goals with minimal operational overhead, we modularize the transactional core in place and extract only the two components with genuinely different resource or failure profiles:
[Customer App / Web] [Dealer Portal] \ / +---------> [API Gateway] <-------+ (routing & flags) / \ v v +-----------------------------------------+ +-------------------------------+ | Core Modular Monolith (18 small pods) | | Availability Search Service | | | | (6 RAM pods, 20 GB index ea.) | | [Booking] --in-proc--> [PartsApi] | +---------------^---------------+ | [Payments] [DealerAdmin] | | | (ArchUnit / import-linter checked CI) | | async events +--------------------+--------------------+ +---------------+---------------+ | | Event Bus (Kafka) | v +---------------+---------------+ [PostgreSQL: 1 schema per module] | (booking.*, parts.*, payments.*, outbox) --outbox relay--->+ v +-------------------------------+ | Notification Worker (SMS/Mail)| | (independent retries & rate) | +-------------------------------+Booking,Parts,Payments, andDealerAdminstay inside the Modular Monolith: Booking + Parts retain their 1-commit ACID transaction, and18lightweight CPU instances need only2 GBof RAM each (36 GBvs.480 GB).Availability Searchis extracted: Saves360 GBof RAM, scales independently during Monday browsing spikes, and tolerates 1–2 seconds of event lag becauseBookingperforms the authoritative check at commit time.Notification Workerbecomes asynchronous: Third-party SMS slowdowns never block customer booking confirmations.
Deep dive 1: Incremental monolith-to-services migration (Strangler Fig)
A "stop feature work for 9 months and rewrite everything" project almost always stalls. Instead, use the Strangler Fig pattern—incrementally building new modules or services alongside the live system behind a routing facade, migrating one slice at a time until old code can be deleted safely:
- Phase 0 — Baseline metrics (2 weeks): Record the four DORA metrics (deployment frequency, change lead time, change failure rate, mean time to recovery), CI runtime, p99 latency, and RAM cost so every later phase proves its value objectively.
- Phase 1 — Modularize in place: Group classes into
booking,parts,payments,dealer_admin, andsearchpackages; enforce dependency rules in CI (for exampleArchUnitin Java orimport-linterin Python) so cross-module private imports fail the build; run only affected module tests on PRs (cutting CI from55 minto~10 min); decouple releases using trunk-based feature flags. - Phase 2 — Extract
Availability Searchvia Branch-by-Abstraction + Shadow Mode:- Wrap monolith search callers behind
AvailabilitySearchApicontrolled by a runtime flag. - Feed the new Search Service from database outbox events.
- Run shadow mode (execute both old monolith code and new Search Service asynchronously on live traffic, return the old result to users, and log response diffs). Once mismatches drop below
< 0.1%(attributable only to sub-second event lag), ramp live traffic1% -> 10% -> 50% -> 100%, keep instant flag rollback for 2 weeks, then delete the 20 GB monolith index.
- Wrap monolith search callers behind
- Phase 3 — Extract async
Notification Workeroff committed outbox events. - Phase 4 — Re-measure and stop! If lead time is
<= 2days and rollback rate is< 10%, stop extracting. Every further service split must justify its own ongoing operational tax.
Deep dive 2: Untangling shared database ownership safely
If you extract a
Parts Servicebinary while bothBookingandPartskeep reading and writingpart_reservationsin PostgreSQL, you have built a distributed monolith: a schema migration onpart_reservationsstill breaks both services simultaneously, and row lock contention crosses service boundaries. Untangle shared tables in four reversible stages:Stage 1 (Logical): Same DB instance, separate schemas (booking.*, parts.*). Only Parts code touches parts.* tables (enforced by DB roles / CI rules). Stage 2 (No joins): Drop cross-schema SQL JOINs and foreign keys. Booking calls PartsApi; analytics JOINs move to a read warehouse via CDC. Stage 3 (Events): Owner writes table update + outbox row in ONE local transaction. Outbox relay streams events to consumers' private read models. Stage 4 (Physical): Stream parts.* to dedicated Parts DB via CDC -> verify row checksums -> brief write cutover -> keep reverse CDC running 7 days for safe rollback.Two terms here are essential:
- Transactional outbox vs. dual-write bug: If code updates PostgreSQL and then calls
kafka.send(), a crash between lines 1 and 2 leaves the database updated with no event sent (the dual-write bug). Writing the event into anoutboxtable inside the same SQL commit guarantees both succeed or both roll back. - CDC (Change Data Capture): A tool (such as Debezium) that tails the database's internal write-ahead log and streams row changes continuously with near-zero impact on query performance.
- Transactional outbox vs. dual-write bug: If code updates PostgreSQL and then calls
Deep dive 3: Keeping business invariants intact across network calls
Suppose the Parts organization grows to 40 engineers supporting external wholesale buyers and genuinely needs
Partsdeployed as an independent microservice. Look closely at what happens to our core business invariant—"A confirmed appointment always holds both a bay slot and reserved parts, and no part unit is ever double-reserved"—the instantPartsApi.reserve_parts(...)crosses a network cable, even if the business logic inside both functions is unchanged:BEFORE (Modular Monolith: 1 in-process ACID transaction) BEGIN -> reserve bay -> decrement brake_pad -> mark CONFIRMED -> COMMIT Outcome: 100% all-or-nothing. Zero partial states ever visible. AFTER (Microservice split: 2 separate databases + network hop) [Booking DB] Network RPC / Event [Parts DB] 1. Write PENDING ------- ReserveParts(apt_42) -------> 2. Decrement brake_pad & COMMIT! <------ X (response packet lost!) --- 3. Timeout! Did Parts commit or crash beforehand? - Naive retry without idempotency key -> decrements a SECOND brake_pad! - Booking gives up without releasing -> brake_pad leaked forever! - Parts auto-expires on its own timer while "Reserved" event was delayed in flight -> Booking marks CONFIRMED after Parts already gave that brake_pad to someone else!When a network boundary cuts across an invariant, replace the lost ACID transaction with an explicit idempotent Saga (a sequence of local transactions coordinated via messages and explicit compensating actions that undo earlier steps when later steps fail):
- Expose the intermediate state honestly:
Bookinginsertsapt_42withstatus = 'PENDING'plus anoutboxeventReservePartsRequested(apt_42)in one local transaction. - Single decision owner (
Booking): Never let both services run independent timeout timers! OnlyBookingdecides final confirmation or cancellation. Ifapt_42stays'PENDING'past 10 minutes,Booking's reconciler transitionsapt_42to'REJECTED'and emitsReleasePartsRequested(apt_42).Partsreleases stock only when commanded byBooking, leaving a'released'tombstone row keyed byapt_42so a super-lateReservePartsRequestedpacket cannot resurrect the reservation. - Idempotent, deadlock-free, atomic stock updates on the
Partsside:
def handle_reserve_request(db, appointment_id: str, part_numbers: list[str]) -> dict: """Parts Service handler. Uses appointment_id as an idempotency key.""" # Fast replay check (also catches tombstones if Booking already timed out and released!). existing = db.find_reservation(appointment_id) if existing is not None: return existing # Sort part numbers so concurrent orders for ["oil_filter", "wiper"] and # ["wiper", "oil_filter"] always lock rows in alphabetical order (zero deadlocks). ordered_parts = sorted(part_numbers) with db.transaction(): # Unique constraint on reservations(appointment_id) serializes simultaneous duplicates. all_in_stock = True # Wrap stock decrements in a SAVEPOINT so if part #2 is out of stock, # we roll back part #1's decrement before recording status="unavailable"! with db.savepoint() as sp: for part_no in ordered_parts: decremented = db.execute_conditional_decrement(part_no) if not decremented: all_in_stock = False sp.rollback() break status = "reserved" if all_in_stock else "unavailable" db.insert_reservation(appointment_id, ordered_parts, status) db.insert_outbox_event( "parts.reservation_outcome", {"appointment_id": appointment_id, "status": status}, ) return {"appointment_id": appointment_id, "status": status} def handle_release_request(db, appointment_id: str) -> None: """Compensating action: releases reserved stock at most once and writes a tombstone.""" with db.transaction(): existing = db.find_reservation_for_update(appointment_id) if existing is None: # Reserve message has not arrived yet! Plant a "released" tombstone so # if ReservePartsRequested arrives later, handle_reserve_request skips it. db.insert_reservation(appointment_id, [], "released") elif existing["status"] == "reserved": for part_no in sorted(existing["part_numbers"]): db.increment_stock(part_no) db.update_reservation_status(appointment_id, "released")Notice the two subtle bugs that code prevents: sorting
ordered_partseliminates cross-part deadlocks, and rolling back thesavepointwhen part #2 is out of stock prevents leaking part #1 while committing the"unavailable"record and outbox event!- Expose the intermediate state honestly:
Deep dive 4: Consolidating an over-fragmented microservice system
In Scenario B (
60services for25engineers,7synchronous hops per booking), the system suffers all the latency and pager pain of distribution with zero deployment independence. We consolidate using objective coupling signals:- Deploy co-occurrence (
> 75%): Services released together in 3 out of 4 deployments are already one deployment unit in disguise. - Synchronous call chains and chatty fan-out: Service pairs making multiple synchronous calls per user click.
- Shared writable tables or single-operation sagas: Compensation code written purely because one ACID transaction was chopped across three tiny repositories.
BEFORE (Scenario B: 7 synchronous network hops, 99.30% composite availability, 1.8 s p99) [Gateway] -> [AuthSvc] -> [CustomerSvc] -> [ApptSvc] -> [BaySvc] -> [PartCheckSvc] -> [PartHoldSvc] -> [FeeSvc] AFTER (Consolidated into coarse modular services aligned to the 4 teams, 99.80% availability, < 0.6 s p99) [Gateway] -> [Booking & Inventory Service] (internal modules: appt, bay, parts -> 1 ACID tx!) -> [Payments Service] (isolated PCI compliance scope) + [Availability Search Service] (read-only RAM profile)Reverse Strangler Fig merge steps:
- Bring related services (
ApptSvc,BaySvc,PartHoldSvc) into one service deployable as strictly separated internal modules keeping their existing*Apiinterfaces. - Behind a feature flag, switch
PartsApifrom its HTTP/gRPC client adapter to an in-process module adapter (zero business-code rewrite, instant rollback if needed). - Migrate schemas into one PostgreSQL cluster (still separate
appt.*,bay.*,parts.*schemas), collapse the fragile 3-service saga back into one clean ACID transaction, and delete hundreds of lines of retry/compensation plumbing. - Isolate modules inside the merged process with bulkheads (separate thread pools and DB connection pools per module) so a slow Dealer Admin export cannot exhaust Booking threads, then decommission the retired pipelines.
- Deploy co-occurrence (
Safety nets, failure handling, and proving migration success
Whether extracting or consolidating, enforce four guardrails until metrics confirm the win:
- Backward-compatible expand-and-contract APIs + contract tests: Add new fields first, migrate callers second, delete old fields last, verified in CI by consumer-driven contract tests (automated checks ensuring a provider change never breaks any caller's expected payload shape).
- Resilient remaining network hops: Every cross-service call sets an explicit timeout, carries an idempotency key on bounded retries, and sits behind a circuit breaker (an automatic trip-switch that fails fast or returns a fallback when a downstream service errors repeatedly, preventing thread pile-ups). For example, if
Availability Searchgoes down,Bookingfalls back to checking a single dealer's live schedule directly. - Continuous invariant reconciliation: Run an hourly background check querying for confirmed appointments missing part reservations or negative/leaked stock counts, paging immediately on any non-zero count.
- Verify against Phase 0 baselines: Compare lead time, rollback rate, RAM spend, p99 latency, and weekly pages against Phase 0 numbers before declaring victory or starting another split.
Summary decision guide
Situation Recommended Architecture ----------------------------------------------- ----------------------------------------------------- 1-3 teams, evolving domain, shared transactions Modular Monolith (1 deploy, strict module schemas) 4-15 teams, mostly CRUD + 1-2 heavy workloads Modular Monolith Core + 1-3 targeted services Large org, distinct domains, independent SLAs Coarse Modular Services (1-2 services/team, no shared DB) Many tiny services deploying in lockstep Consolidate along bounded contexts & transaction lines
Intuition & how it works
Think of organizing a growing restaurant kitchen: a plain monolith is one wide-open counter where every cook reaches into any fridge or pan drawer (effortless for 3 cooks, chaotic for 50); a modular monolith keeps everyone under one roof (one deployment and one shared ACID database transaction, meaning multi-step updates succeed completely or roll back completely), but divides the kitchen into strict stations—grill, pastry, prep—that pass plates only through labeled windows enforced by automated build rules; microservices put each station in a separate building across town connected by delivery vans (worth the cost when an industrial bakery needs giant ovens on cheap land, disastrous if plating one burger requires 7 van trips through rush-hour traffic!).
Why do naive migrations fail in both directions? Chopping a tangled monolith into dozens of microservices before cleaning up code and table ownership turns nanosecond function calls into millisecond network hops over the exact same shared database—producing a distributed monolith that still deploys in lockstep while suffering lower availability and higher tail latency. Worse, moving identical business code across a network cable silently breaks business invariants because networks lose responses, time out with unknown outcomes, and duplicate retried requests. Going the other way, dumping 60 tiny microservices into one Git repository without collapsing their network RPCs and sagas back into in-process module calls saves zero latency or on-call toil.
Let's trace one concrete dealership operation—Customer books Appointment #42 needing Bay 3 + Brake Pad P9 (last unit in stock)—across three architectures:
1. Modular Monolith (in-process module boundary, 1 PostgreSQL ACID transaction):
- Booking calls PartsApi.reserve_parts("apt_42", ["P9"]) in memory (~50 ns).
- BEGIN -> lock Bay 3 -> decrement P9 (1 -> 0) -> insert apt_42 CONFIRMED -> COMMIT (~6 ms).
- If Bay 3 is taken or P9 == 0, ROLLBACK leaves zero half-finished state!
2. Naive Microservice Split (same code copied behind HTTP, no saga/idempotency):
- Booking calls POST parts-service/reserve {"part": "P9"} -> Parts commits P9 (1 -> 0),
but a brief network blip drops the HTTP 200 response!
- Booking sees a timeout, retries -> Parts rejects (P9 == 0!), Booking tells customer "Failed",
and that last Brake Pad P9 sits leaked at 0 forever with no appointment attached!
3. Proper Idempotent Saga (when Parts MUST be a separate service):
- Booking commits apt_42 as PENDING + outbox event ReserveParts("apt_42", ["P9"]).
- Parts keys reservations by appointment_id ("apt_42"): the retry returns the stored
{"status": "reserved"} receipt instead of double-decrementing!
- If Booking already timed out after 10 min, Booking sends ReleaseParts("apt_42"), which
plants a "released" tombstone in Parts so even a delayed reserve message cannot leak P9.
Key trade-offs
- Plain monolith vs. modular monolith: Both run as a single deployable unit with one CI/CD pipeline and shared ACID transactions, avoiding distributed-systems complexity. Adding CI-enforced module APIs and per-module database schemas in a modular monolith costs upfront boundary discipline and removes shortcut SQL joins, in exchange for letting multiple teams work in parallel without turning the codebase into spaghetti—while keeping future service extraction cheap.
- Modular monolith vs. microservices: Microservices unlock independent scaling for asymmetric workloads (such as a
20 GBRAM search index vs. lightweight CRUD APIs), hard process/security isolation, and fully independent release cadences. In return, you pay serialization and network latency on every boundary crossing, lose cross-service ACID transactions, multiply failure rates across synchronous chains (0.999^7 = 99.30%), and carry a fixed operational tax per service (pipelines, dashboards, certs, and SDK upgrades). - Synchronous RPC chains vs. asynchronous event-driven integration: Synchronous HTTP/gRPC calls feel like ordinary function calls and return immediate answers, but tightly couple caller uptime and tail latency (
1 - 0.99^7 = 6.8%of 7-hop requests hit at least one p99 stall). Asynchronous events published via a transactional outbox (writing the event row in the same DB commit as the business update) decouple availability and absorb spikes, at the cost of eventual consistency (read models lag by a second or two) and harder end-to-end debugging. - Keeping invariants inside one service vs. cross-service Sagas: Aligning service boundaries around transactional business invariants gives exact, effortless consistency. Cutting a service boundary through an invariant forces you to expose intermediate
'PENDING'states to users and maintain Saga state machines, idempotency tables, compensating actions, and background reconcilers. - Logical schema separation vs. immediate physical database split: Separating
booking.*andparts.*schemas inside one PostgreSQL cluster captures 80% of data-ownership clarity immediately with zero operational overhead, whereas physically splitting into separate database clusters unlocks independent DB scaling and blast-radius isolation at the cost of CDC (Change Data Capture) migrations and losing local ACID commits. - Consolidating into coarse modular services vs. fine-grained microservices: Merging 60 tiny services into 6–8 team-aligned modular services eliminates chatty network hops, collapses brittle sagas back into ACID transactions, and slashes DevOps overhead, at the trade-off of a wider process blast radius that must be contained with internal bulkheads (separate thread and connection pools per module) and feature flags.
Common mistakes
- Choosing microservices before measuring the bottleneck: Splitting a slow-shipping monolith because of a 55-minute CI pipeline or merge conflicts—problems solved far more cheaply by modular build caching and trunk-based feature flags—adds network outages without speeding up teams.
- Equating "more services" with "higher scalability": Stateless monolith pods scale horizontally behind a load balancer just fine; extracting CPU-bound CRUD endpoints into 20 microservices only adds JSON/Protobuf serialization CPU overhead.
- Extracting service code while leaving database tables shared and multi-writable: Two services reading and writing
part_reservationsremain coupled at deployment and lock-contention time, creating a distributed monolith with extra latency. - Lifting code across a network boundary without handling ambiguous timeouts: Assuming a timed-out RPC "did not happen" causes double charges or double stock reservations on retry, or permanently leaked inventory when abandoned.
- Dual writes (
db.commit()followed bybus.publish()): A process crash or broker blip between the database commit and the message publish silently drops the event and leaves downstream search/notification state permanently out of sync; always use a transactional outbox or CDC. - Letting both sides of a Saga expire state on independent timers: If
Partsauto-releases a reservation att = 5mwhile its"PartsReserved"message was delayed in a queue and reachesBookingatt = 5m02s,Bookingconfirms an appointment whose parts were already given to another customer; one coordinator (Booking) must own timeout decisions and issue explicit release commands. - Splitting by technical layer instead of business capability: Creating an
"Entity DB Service","Rules Service", and"Orchestrator Service"forces every product change and every user click to touch all three services simultaneously. - "Consolidating" into a monorepo while keeping HTTP calls between tiny services: Moving code into one repository without swapping network clients for in-process module calls keeps all runtime latency, saga complexity, and deployment ordering pain intact.
Follow-up questions
- What practices prevent extracted services from degenerating into a lockstep-deployed distributed monolith? Treat independent deployability as an enforced invariant: every service must own its private database tables exclusively (zero shared tables or cross-service SQL joins) and never share a "common domain library" whose version bump forces simultaneous rebuilds. Evolve every network API and event schema strictly through backward-compatible expand-and-contract steps (add optional fields first, migrate consumers, drop old fields later) gated in CI by consumer-driven contract tests so any single service can deploy or roll back at any hour without breaking neighbors. Prefer asynchronous outbox events for read models and side effects, cap synchronous user-path chains to at most 1–2 hops, and track deploy co-occurrence—if two services still ship together in > 75% of releases, redraw or merge their boundary.
- How does multiple components reading and writing the same database tables reshape your service-extraction sequence? Shared tables dictate both the order and the cost of extraction, because code movement takes days while untangling shared writes and transactions takes weeks. Start by building a table-access (
R/W) and transaction matrix: extract read-only consumers (likeAvailability Search) first via outbox/CDC events, and keep modules sharing tight ACID invariants (likeBookingandParts) together unless a compelling scale or organizational need justifies building an idempotent Saga. Before moving any writable service out, enforce single-module write ownership inside the existing database (separate schemas, revoked cross-schema write grants, zero cross-module SQL joins or foreign keys, analytics moved to a CDC warehouse), and only then perform the physical database split using live CDC replication, row-checksum verification, a brief write switchover, and 7-day reverse replication for instant rollback.
Follow-up questions
- What practices prevent extracted services from degenerating into a lockstep-deployed distributed monolith?
- How does multiple components reading and writing the same database tables reshape your service-extraction sequence?
Similar questions
- Hitting Sub-10s Latency and 99% Availability Across Downstream Services
- End-to-End Reliability Loop for Fleet Telemetry Ingestion
- Connected Islands in a Binary Matrix
- Vehicle Telemetry GET Endpoint and Safe API Versioning
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor