Microservices Architecture
Microservices is an architectural style that structures an application as a collection of small, autonomous services, modeled around a business domain. Ideally, each service does one thing and does it well.
1. Monolith vs. Microservices
-
Monolithic Architecture: The traditional way of building applications. All functionalities (User Auth, Payments, Inventory) are bundled into a single codebase and deployed as a single unit.
- Pros: Simple to develop initially, easy to deploy (one file).
- Cons: Hard to scale specific parts, a bug in one module can crash the whole app, technology lock-in (entire app must be upgraded together).
-
Microservices Architecture: The application is broken down into smaller, independent services.
- Pros: Independent scaling (scale just the "Payment" service during Black Friday), technology diversity, fault isolation.
- Cons: Complex to manage (DevOps heavy), network latency, data consistency challenges.
2. Key Characteristics
- Independently Deployable: You can update the "Payment Service" without redeploying the "User Service".
- Loose Coupling: Services communicate via well-defined APIs (usually REST or gRPC). They generally do not share database tables.
- Organized around Business Capabilities: Instead of organizing by technical layers (UI, DB, Logic), teams are organized by business goals (Checkout, Shipping).
- Polyglot: Different services can be written in different languages (e.g., Python for AI, Node.js for I/O, Java for enterprise logic).
3. Communication
Since services run in separate processes (or even separate servers), they need to communicate over a network.
- Synchronous: HTTP/REST, gRPC. (Service A sends a request to Service B and waits for a response).
- Asynchronous: Message Queues (RabbitMQ, Kafka). (Service A sends a message/event and moves on; Service B processes it later).
4. Database per Service
A core pattern is that each microservice owns its own data. Other services cannot access that database directly; they must go through the service's API.
- Benefit: Changes to one service's schema don't break other services.
- Challenge: Implementing transactions that span multiple services is difficult (often requires patterns like Sagas).
5. Example Scenario: E-Commerce
Instead of one giant app, you might have:
- Product Service: Stores product details and inventory. (Database: MongoDB)
- Order Service: Handles placing orders. (Database: PostgreSQL)
- Payment Service: Integrates with Stripe/PayPal. (Database: MySQL)
- Notification Service: Sends emails/SMS. (No DB, just a queue consumer)
If the Notification Service crashes, users can still buy products. In a monolith, a memory leak in the email code might crash the checkout process.
programming/rest-apis programming/database-basics programming/asynchronous-programming