- Part 8 of 21 in System Design Roadmap: From Beginner to Intermediate Architecture Beginner
Monolithic vs Microservices: Architecting Scalable Software Systems
Evaluate the architectural trade-offs between monolithic systems and microservices, implement both paradigms, and handle distributed communication challenges.
MonksBit Desk
November 21, 2026 · 9 min read · 50 views
Read
A monolithic architecture packages all business capabilities, UI routing, and data access into a single unified codebase running in one runtime process. A microservices architecture decomposes an application into independent, loosely coupled services, where each service owns its own data store and communicates over a network protocol.
You will need. Basic knowledge of client-server network architecture · Familiarity with HTTP requests and JSON data formats · Understanding of relational databases and foreign keys
The full lesson
Level 1 · Beginner: Understanding the Fundamentals of Single-Process and Multi-Process Design
In software development, architecture defines how components are organised and how they communicate with each other. The simplest and most traditional model is the monolith. In a monolith, code responsible for user management, inventory tracking, payment processing, and notifications is compiled together and deployed as one executable unit onto an operating system. Function calls between these business domains happen in memory, which is nearly instantaneous and inherently reliable within that process.
As an organisation grows, maintaining a monolith can present challenges when multiple teams modify the same codebase, or when one specific feature requires massive computing resources while the rest remain idle. Microservices address this by isolating each business capability into a distinct executable program. Instead of calling an in-memory method like process_payment(), the order component sends an HTTP request or message over a network interface to a dedicated payment service.
To compare the operational reality, imagine an e-commerce checkout flow. In a monolithic setup, placing an order executes within a single database transaction: verify inventory, record order, debit balance. If any step fails, the database driver rolls back the entire transaction automatically. In a microservices setup, inventory, orders, and payments are distinct programs with their own private databases. The order service must coordinate with the inventory service and payment service independently, meaning network retries, failure handling, and distributed state must now be explicitly managed.
In-memory monolithic order processing using standard method invocation
class InventoryModule: def __init__(self): self.stock = {"item_1": 10} def reserve(self, item_id: str, quantity: int) -> bool: if self.stock.get(item_id, 0) >= quantity: self.stock[item_id] -= quantity return True return Falseclass PaymentModule: def charge(self, user_id: str, amount: float) -> bool: # Direct in-memory simulated card charge return amount > 0class MonolithicStore: def __init__(self): self.inventory = InventoryModule() self.payment = PaymentModule() self.orders = [] def place_order(self, user_id: str, item_id: str, quantity: int, price: float) -> str: if not self.inventory.reserve(item_id, quantity): return "OUT_OF_STOCK" if not self.payment.charge(user_id, price * quantity): # Rollback inventory in memory self.inventory.stock[item_id] += quantity return "PAYMENT_FAILED" order_id = f"ORD-{len(self.orders) + 1}" self.orders.append({"order_id": order_id, "user_id": user_id, "item_id": item_id}) return order_idstore = MonolithicStore()print(store.place_order("user_101", "item_1", 2, 29.99))
Key takeaways
- Monoliths execute all business logic inside a single operating system process.
- Microservices separate responsibilities into distinct services communicating over networks.
- In-process method calls are reliable and fast; network calls introduce latency and failure modes.
Level 2 · Intermediate: Network Boundaries, Data Isolation, and Contract-Based Communication
Moving to microservices requires strict data isolation. A fundamental rule of microservices is that no service may directly query or write to another service's database. If the order service could query the inventory database table directly, changes to the inventory schema would silently break the order service, destroying deployment autonomy. Each service must expose an explicit application programming interface (API), usually via REST HTTP or gRPC, that acts as an immutable boundary.
Network boundaries introduce partial failures. In a monolith, calling a function either returns a result or raises an unhandled exception. In microservices, the remote service might crash, the network route might drop packets, or the host might take too long to respond. The calling service must configure timeouts, handle transient connection resets, and verify data contracts. If the payment service times out, the client cannot know whether the card was charged or if the request dropped before reaching the server.
Testing microservices requires shifting focus toward integration and contract testing. While unit tests verify the internal logic of a single service, contract tests verify that changes to a service's API do not break downstream consumers. Furthermore, local development changes from launching a single Python script to running multiple processes or container definitions using Docker Compose.
Microservices client with timeout enforcement and network failure handling
import jsonimport urllib.requestimport urllib.errorclass InventoryServiceClient: def __init__(self, base_url: str, timeout_seconds: float = 2.0): self.base_url = base_url.rstrip("/") self.timeout = timeout_seconds def reserve_stock(self, item_id: str, quantity: int) -> bool: url = f"{self.base_url}/inventory/reserve" payload = json.dumps({"item_id": item_id, "quantity": quantity}).encode("utf-8") request = urllib.request.Request( url, data=payload, headers={"Content-Type": "application/json"}, method="POST" ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: if response.status == 200: data = json.loads(response.read().decode("utf-8")) return data.get("reserved", False) return False except (urllib.error.URLError, TimeoutError): # Network failure, timeout, or DNS resolution failure handled gracefully return Falseclient = InventoryServiceClient("http://127.0.0.1:8081")# Simulated network call attempting to reserve 2 unitsreservation_status = client.reserve_stock("item_1", 2)print(f"Reservation success: {reservation_status}")
Key takeaways
- Every microservice must own its database exclusively to prevent tight coupling.
- Remote procedure calls must always define timeouts and handle dropped connections.
- Contract stability replaces internal function signature stability.
Level 3 · Advanced: Distributed Consistency, Resiliency Patterns, and Sagas
In a distributed system, traditional two-phase commit protocols across microservices do not scale and introduce severe availability bottlenecks according to the CAP theorem. Instead, microservices rely on eventual consistency using patterns such as the Saga pattern. A Saga is a sequence of local transactions where each service updates its internal database and publishes a message or event. If a subsequent step fails, compensating transactions are triggered to undo preceding state changes.
Resilience patterns such as circuit breakers, retries with exponential backoff and jitter, and bulkhead isolation are necessary to prevent cascading failures. If Service A continually calls a degraded Service B, Service A's thread pool will exhaust itself waiting for timeouts, collapsing upstream services. A circuit breaker tracks failures and rapidly fails future requests once an error threshold is reached, granting Service B time to recover.
Choosing between these architectures is primarily an organisational and operational trade-off, not a pure performance choice. Monoliths offer lower infrastructure overhead, simpler debugging, single-step deployments, and zero network serialization latency. Microservices offer team autonomy, independent deployability, and granular horizontal scaling at the cost of high operational complexity, distributed tracing requirements, and eventual consistency challenges.
Orchestrated Saga pattern with automatic compensating transactions
from dataclasses import dataclassfrom typing import Callable, List, Tuple@dataclassclass SagaContext: order_id: str user_id: str item_id: str quantity: int amount: float inventory_reserved: bool = False payment_processed: bool = Falseclass CheckoutSagaOrchestrator: def __init__(self): self.steps: List[Tuple[str, Callable[[SagaContext], bool], Callable[[SagaContext], None]]] = [] def add_step(self, name: str, action: Callable[[SagaContext], bool], compensate: Callable[[SagaContext], None]): self.steps.append((name, action, compensate)) def execute(self, ctx: SagaContext) -> bool: executed_steps = [] for name, action, compensate in self.steps: try: success = action(ctx) if not success: self._rollback(executed_steps, ctx) return False executed_steps.append((name, compensate)) except Exception: self._rollback(executed_steps, ctx) return False return True def _rollback(self, executed_steps, ctx: SagaContext): for name, compensate in reversed(executed_steps): try: compensate(ctx) except Exception as e: # In production, publish to a dead-letter queue for operator remediation print(f"Critical compensation failure in {name}: {e}")saga = CheckoutSagaOrchestrator()saga.add_step( "ReserveInventory", action=lambda ctx: setattr(ctx, 'inventory_reserved', True) or True, compensate=lambda ctx: setattr(ctx, 'inventory_reserved', False))saga.add_step( "ProcessPayment", action=lambda ctx: False, # Simulating card decline compensate=lambda ctx: setattr(ctx, 'payment_processed', False))context = SagaContext("ORD-1", "U-10", "SKU-9", 1, 49.99)success = saga.execute(context)print(f"Saga completed: {success}, Inventory state: {context.inventory_reserved}")
Key takeaways
- Distributed transactions require compensating actions via the Saga pattern instead of locking databases.
- Circuit breakers protect services from cascading thread exhaustion caused by downstream outages.
- Monoliths optimize for development simplicity; microservices optimize for team autonomy at the cost of operational overhead.
Complexity
- Time: Monolith request: O(1) in-memory call overhead; Microservices request: O(k) cumulative network and serialization latency across k hops
- Space: Monolith memory: O(N) single shared memory pool; Microservices memory: O(N + k * M) base runtime footprint overhead per service container
Monoliths communicate via machine-level stack calls which execute in nanoseconds, requiring no packet serialization. Microservices transform domain entities into JSON, protobuf, or byte streams, transit virtual or physical network switches, and incur socket read/write overhead across each dependency boundary.
Common mistakes
- Sharing a single database between multiple microservices, which creates tight coupling and eliminates independent deployability.
- Prematurely adopting microservices for a small team or brand-new product before business domain boundaries are understood.
- Making synchronous chained REST calls across many services without timeouts, causing thread starvation and cascading system failure.
- Forgetting to design compensating transactions for multi-step distributed operations, resulting in corrupted or orphaned data states.
Practice problems
- Modular Monolith Boundary Separation (easy). Hint: Ensure internal domains communicate solely via clean interface functions rather than accessing other module state variables directly.
- Idempotent Network Retries (medium). Hint: Attach a unique request identifier header so that repeating a failed network attempt does not create duplicate charges or reservations.
- Distributed Transaction Orchestration with Compaction (hard). Hint: Track state transitions durably on disk so that an orchestrator can resume or compensate steps after an unexpected crash.
Summary
Monolithic architectures consolidate logic and storage into a single process, simplifying development, local testing, and data consistency. Microservices split business capabilities into independently deployable networked applications, trading simplicity for independent team scaling and operational autonomy. Successful architecture matches system requirements and team size to the appropriate trade-offs of latency, complexity, and failure modes.
Finish the Prove step above to complete this lesson.
System Design Roadmap: From Beginner to Intermediate Architecture · 8 of 21
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!