Microservices Architecture
Build microservices with Node.js. Learn service communication.
Microservices Architecture
Monolith vs Microservices
**Monolith:** ``` One big application ├── User management ├── Orders ├── Payments └── Notifications
All in one codebase, one database, one deployment ```
**Microservices:** ``` Multiple small services ├── User Service (port 3001) ├── Order Service (port 3002) ├── Payment Service (port 3003) └── Notification Service (port 3004)
Each has own codebase, database, deployment ```
Benefits
- **Independent deployment** - Update one service without affecting others - **Technology flexibility** - Use different tech for different services - **Better scalability** - Scale only services that need it - **Fault isolation** - One service crash doesn't kill everything
Basic Service Structure
```javascript // user-service/index.js const express = require('express'); const app = express();
app.get('/users/:id', async (req, res) => { const user = await User.findById(req.params.id); res.json(user); });
app.listen(3001); ```
```javascript // order-service/index.js const express = require('express'); const app = express();
app.get('/orders/:id', async (req, res) => { const order = await Order.findById(req.params.id); res.json(order); });
app.listen(3002); ```
Service Communication
```javascript const axios = require('axios');
app.get('/orders/:id', async (req, res) => { const order = await Order.findById(req.params.id); const userResponse = await axios.get( `http://user-service:3001/users/${order.userId}` ); res.json({ ...order.toObject(), user: userResponse.data }); }); ```
API Gateway
```javascript const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api/users', createProxyMiddleware({ target: 'http://user-service:3001', changeOrigin: true }));
app.use('/api/orders', createProxyMiddleware({ target: 'http://order-service:3002', changeOrigin: true }));
app.listen(3000); ```
Key Takeaway
Microservices enable independent scaling and deployment. Use API gateway as entry point. Each service has own database. Start simple, split when needed.