From a Monolith to Multiple Services
🎯 Introduction
In the previous order example, mock.mjs exposed user, product, and order endpoints on port 4100. Even changing only the user endpoint required restarting that process.
What if you want to start, stop, and update these features separately? Using the existing order data, we will split the mock backend into three independent Express services and have the BFF call them. You will understand how a monolith differs from multiple services, perform the split, and verify service dependencies.
🧱 How Does a Monolith Differ from Multiple Services?
A monolithic application runs multiple business features in one application process. Separate route files such as users-router.mjs and orders-router.mjs still form a monolith if one Express application starts them all. Splitting files or modules is not the same as splitting services.
Before the split, all three endpoints run in the same mock.mjs process on port 4100:
courseComponents.mermaid.loading
After the split, each business area has its own entry file, process, and port:
courseComponents.mermaid.loading
Stopping the user service now leaves the product service process running. However, BFF order details require a user name, so stopping the user service may still prevent order details from displaying correctly. Independent processes do not eliminate business dependencies.
Multiple services do not necessarily constitute microservices. Three processes provide independent execution, but microservices also emphasize clear business boundaries, service autonomy, data ownership, and independent deployment. This article first establishes the basics of splitting services.
💡 When Should You Split an Application into Services?
A larger project does not automatically require a split. Consider the actual problem:
| Project situation | More suitable approach |
|---|---|
| Small project, closely related features, small team | Prefer a monolith with well-organized modules |
| Frequent user feature changes should not interrupt the product service | Consider deploying the user service independently |
| Business areas have very different traffic and scaling needs | Consider separate services |
| Different teams own business areas and want separate releases | Consider splitting services with explicit API contracts |
A split enables independent execution and deployment, but adds processes, service addresses, logs, and network failures to manage. Decide whether the benefits justify those costs.
🧩 Divide User, Product, and Order Services by Responsibility
Keep the existing data and divide services by business responsibility, rather than simply by endpoint count.
| Service | Responsible for | Not responsible for |
|---|---|---|
User service users | User profiles and user existence | Calculating order totals |
Product service products | Product information and current prices | Determining historical prices of existing orders |
Order service orders | Order records, quantities, and totals at purchase | Adapting display fields for different pages |
| BFF | Calling business services and composing page data | Defining actual order pricing rules |
Real projects also need explicit data access boundaries. A BFF should not query user, product, and order tables directly to compose order details; otherwise, business service schema changes may force BFF changes too.
To focus on splitting services, we keep using in-memory arrays without a database. data.mjs supplies initial data for the local example. Each Node.js process imports its own in-memory copy; this is not a shared database solution for services.
🛠 Split One Express Application into Three Services
1. Prepare the Project Files
Continue in the course example directory. Ensure Node.js 22 and Express 5 are installed (run npm install express@5.1.0 if dependencies are not installed). This article uses:
backend-architecture-course/
├── data.mjs # Example data
├── mock.mjs # Original mock backend; no longer started here
├── users.mjs # New: user service
├── products.mjs # New: product service
├── orders.mjs # New: order service
└── bff.mjs # New: BFF calling all three services
Keep your existing data.mjs if you already have it. The required data is:
// data.mjs
export const users = [{ id: 'u1', name: 'Lin', email: 'lin@example.test' }];
export const products = [{ id: 'p1', name: 'Mechanical Keyboard', priceCents: 29900 }];
export const orders = [
{ id: 'o1', userId: 'u1', productId: 'p1', quantity: 2, totalCents: 59800 },
];
2. Create the User Service
Create users.mjs:
import express from 'express';
import { users } from './data.mjs';
const app = express();
app.get('/users/:id', (req, res) => {
const user = users.find(item => item.id === req.params.id);
if (!user) {
return res.status(404).json({ error: 'USER_NOT_FOUND' });
}
res.json(user);
});
app.listen(4001, '127.0.0.1', () => {
console.log('users service on 4001');
});
express() creates a separate application, app.get() exposes a user query endpoint, and app.listen(4001) listens on port 4001. It can serve user data without starting the product or order services.
3. Create the Product and Order Services
Create products.mjs to handle product queries only:
import express from 'express';
import { products } from './data.mjs';
const app = express();
app.get('/products/:id', (req, res) => {
const product = products.find(item => item.id === req.params.id);
if (!product) {
return res.status(404).json({ error: 'PRODUCT_NOT_FOUND' });
}
res.json(product);
});
app.listen(4002, '127.0.0.1', () => {
console.log('products service on 4002');
});
Then create orders.mjs to handle order queries only:
import express from 'express';
import { orders } from './data.mjs';
const app = express();
app.get('/orders/:id', (req, res) => {
const order = orders.find(item => item.id === req.params.id);
if (!order) {
return res.status(404).json({ error: 'ORDER_NOT_FOUND' });
}
res.json(order);
});
app.listen(4003, '127.0.0.1', () => {
console.log('orders service on 4003');
});
These files have similar structures, but run in three separate Node.js processes with their own ports. To make the split easy to follow, we do not yet use shared helpers such as createApp() or finish().
4. Update the BFF to Call Three Addresses
Previously, all three requests in minimal-bff.mjs went to 4100. Business endpoints now use different ports, so choose the address by service. Create bff.mjs:
import express from 'express';
const app = express();
const services = {
users: 'http://127.0.0.1:4001',
products: 'http://127.0.0.1:4002',
orders: 'http://127.0.0.1:4003',
};
async function read(service, path) {
const response = await fetch(`${services[service]}${path}`);
if (!response.ok) {
throw new Error(`${service} returned ${response.status}`);
}
return response.json();
}
app.get('/bff/orders/:id', async (req, res) => {
const orderId = encodeURIComponent(req.params.id);
const order = await read('orders', `/orders/${orderId}`);
const [user, product] = await Promise.all([
read('users', `/users/${encodeURIComponent(order.userId)}`),
read('products', `/products/${encodeURIComponent(order.productId)}`),
]);
res.json({
id: order.id,
customerName: user.name,
productName: product.name,
totalCents: order.totalCents,
});
});
// Simplified for teaching: return 502 for unavailable upstreams or unsuccessful statuses.
app.use((error, req, res, next) => {
res.status(502).json({ error: 'UPSTREAM_ERROR' });
});
app.listen(4000, '127.0.0.1', () => {
console.log('bff on 4000');
});
The request addresses change; the aggregation rules stay the same. The BFF still fetches the order first, queries user and product concurrently, then returns the required fields. “Implementing API Aggregation with Node.js” already covered Promise.all, so we will not repeat it here.
This BFF still uses minimal error handling: all upstream request failures return 502. Production also requires timeouts, logging, and error classification, covered later in “Handling Service Call Failures.”
🧪 Start the Services and Verify Their Independence
1. Start Four Separate Processes
Stop the existing mock.mjs and minimal-bff.mjs processes so the old BFF does not occupy port 4000. Open four terminals and run one command in each:
# Terminal A: user service
node users.mjs
# Terminal B: product service
node products.mjs
# Terminal C: order service
node orders.mjs
# Terminal D: BFF
node bff.mjs
Each command keeps running, so use separate terminals. Then run these requests in a fifth terminal:
curl http://127.0.0.1:4001/users/u1
curl http://127.0.0.1:4002/products/p1
curl http://127.0.0.1:4003/orders/o1
curl http://127.0.0.1:4000/bff/orders/o1
Expected response bodies, formatted for readability:
User endpoint:
{ "id": "u1", "name": "Lin", "email": "lin@example.test" }
Product endpoint:
{ "id": "p1", "name": "Mechanical Keyboard", "priceCents": 29900 }
Order endpoint:
{ "id": "o1", "userId": "u1", "productId": "p1", "quantity": 2, "totalCents": 59800 }
BFF aggregation endpoint:
{
"id": "o1",
"customerName": "Lin",
"productName": "Mechanical Keyboard",
"totalCents": 59800
}
Each business service returns its own data, and the BFF combines it into a result suited to the page.
2. Stop One Service and Observe the Impact
Press Ctrl + C in the users.mjs terminal to stop only the user service. Keep the other three processes running. The product endpoint should still succeed, but BFF order details return HTTP 502:
curl -i http://127.0.0.1:4000/bff/orders/o1
HTTP/1.1 502 Bad Gateway
...
{"error":"UPSTREAM_ERROR"}
The BFF can fetch the order and product, but still needs the user's name from the user service. Run node users.mjs again; order details recover without restarting the product service, order service, or BFF.
| Running state | User endpoint | Product endpoint | BFF order details |
|---|---|---|---|
| All services running | Success | Success | Success |
| User service stopped | Connection fails | Success | Failure (502) |
| Product service stopped | Success | Connection fails | Failure (502) |
3. Independent Execution Still Requires Compatible APIs
After changing the internal implementation of users.mjs, restart only the user service, not the product service. However, removing the name field read by the BFF prevents it from providing customerName correctly. Services can run independently, but their API contracts must remain compatible.
❓ Questions and Answers
Q1: Must services run on different servers?
No. All three business services and the BFF run on one computer with different ports here. Deploying to different machines is a separate deployment choice.
Q2: Should every database table have its own service?
No. Split by business responsibility, not table count. Order records and pricing rules both belong to the order domain; do not separate them mechanically to achieve “one service per table.”
🧪 Exercise
Add GET /products/p1/availability to the product service, returning:
{ "available": true }
Restart only products.mjs. Verify the new endpoint and confirm that user queries, order queries, and BFF order details still work. Then stop the product service, call those three endpoints again, record the results, and explain them.
Success criteria: Explain which process restarted, which endpoints still work, and why stopping the product service affects the BFF.
🎉 You have split a single-process mock backend into three independently running Express services and tested their dependencies!
