Appearance
Architecture Styles
1. What is the difference between a monolith and microservices?
The short answer
A monolith is one application, built and deployed as a single unit, usually with one database: orders, payments, users and catalogue all live in one codebase and one process. Microservices split the system into small, independently deployable services, each owning one business area and its own data, talking over the network. A monolith is simpler to build, test, deploy and debug. Microservices let many teams work and deploy independently and scale parts separately, at the cost of distributed-systems problems. Most products should start as a modular monolith and split only when a clear need appears.
| Monolith | Microservices | |
|---|---|---|
| Deploy | One unit | Each service separately |
| Data | One database | One database per service |
| Calls between parts | Function calls: fast, reliable | Network calls: slower, can fail |
| Transactions across parts | One database transaction | Sagas and eventual consistency (sagas) |
| Scaling | Scale the whole app | Scale each service |
| Team independence | Low, shared release | High, own release |
| Debugging | One log, one stack trace | Distributed tracing needed |
The modular monolith, the usual best start. One deployable app, but with strict module boundaries: each module has its own folder, its own public interface, its own database tables, and other modules may only call that interface. If one module later needs to become a service, the boundary already exists.
2. What are the advantages and disadvantages of microservices?
The short answer
Advantages: teams can build, deploy and scale their services independently; a bug or overload in one service can be contained; each service can use the technology that fits; and the code a person must understand is smaller. Disadvantages: everything becomes a distributed system, with network failures, latency, retries and partial outages; data consistency across services needs sagas and events instead of transactions; testing, debugging, monitoring and deployment all get much harder; and the operational cost of running dozens of services is high. Microservices solve organisational scaling problems more than technical ones.
| Advantage | The cost that comes with it |
|---|---|
| Independent deploys | Versioned APIs, backward compatibility between services |
| Independent scaling | More infrastructure, service discovery, load balancing |
| Fault isolation | Only if you build timeouts, circuit breakers and fallbacks (resilience) |
| Team autonomy | Coordination through contracts instead of code review |
| Technology choice | More languages and stacks to support |
| Smaller codebases | Logic and data split across the network |
Signs you are ready to split a service out:
- Several teams keep blocking each other's releases in one codebase.
- One part has very different scaling needs, such as image processing.
- One part needs a different reliability or security boundary, such as payments.
- The module boundary is already clean, so splitting is mostly moving code.
The "distributed monolith" trap. Services that must be deployed together, share a database, or call each other synchronously in long chains get every cost of microservices and none of the benefits. Interviewers love asking how you would avoid it.
3. What is MVC architecture?
The short answer
MVC, Model-View-Controller, splits a user-facing application into three roles. The model holds the data and business rules. The view presents data to the user, such as an HTML page or a JSON response. The controller receives input, such as an HTTP request, asks the model to do work, and chooses the view to render. In an Express API, routes and handlers play the controller, your data and domain code is the model, and the JSON serialisation or template is the view. Its weakness is that "model" grows huge unless you add service and repository layers.
ts
// controller: HTTP in, HTTP out, no business rules
export async function createOrderController(req: Request, res: Response) {
const input = CreateOrderSchema.parse(req.body) // (1)
const order = await orderService.placeOrder(req.user!.id, input) // (2)
res.status(201).json(toOrderView(order)) // (3)
}
// view: shape the response
export const toOrderView = (o: Order) => ({ id: o.id, status: o.status, total: formatPence(o.totalPence) })- Validate the input at the edge.
- Hand off to the model side, here a service (question 5).
- The view decides the response shape, so internal fields never leak.
| Role | In an Express API | Must not |
|---|---|---|
| Model | Domain objects, services, repositories | Know about req and res |
| View | Response mappers, templates | Contain business rules |
| Controller | Route handlers | Run SQL or business rules directly |
4. What is the Repository Pattern?
The short answer
A repository is an object that hides how data is stored behind a simple, collection-like interface named in business terms: orders.findById(id), orders.findOpenForCustomer(customerId), orders.save(order). The rest of the code calls the repository instead of writing SQL or ORM queries everywhere. This keeps queries in one place, makes services easier to read, lets you change the database or ORM in one layer, and lets you substitute an in-memory version when exercising the service on its own. Avoid making it a thin copy of every ORM method.
ts
export interface OrderRepository { // (1)
findById(id: string): Promise<Order | null>
findOpenForCustomer(customerId: string): Promise<Order[]>
save(order: Order): Promise<void>
}
export class PgOrderRepository implements OrderRepository {
constructor(private readonly db: Pool) {}
async findById(id: string) {
const { rows } = await this.db.query('SELECT * FROM orders WHERE id = $1', [id])
return rows[0] ? toOrder(rows[0]) : null // (2)
}
async findOpenForCustomer(customerId: string) {
const { rows } = await this.db.query(
"SELECT * FROM orders WHERE customer_id = $1 AND status IN ('pending', 'paid') ORDER BY created_at DESC", [customerId])
return rows.map(toOrder)
}
async save(o: Order) {
await this.db.query(
`INSERT INTO orders (id, customer_id, status, total_pence) VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, total_pence = EXCLUDED.total_pence`,
[o.id, o.customerId, o.status, o.totalPence])
}
}- The interface speaks the business's language, "open orders for a customer", not SQL.
- Map rows to domain objects in one place, so
customer_idcolumns never leak into business code.
Where it earns its keep: complex queries reused in several places, and code that should not care which database it uses. Where it is overkill: a tiny CRUD service where the ORM already reads clearly.
5. What is the Service Layer Pattern?
The short answer
The service layer holds the application's use cases, such as "place an order", "refund a payment" or "invite a teammate", as functions or classes between the controllers and the repositories. Each service method validates business rules, coordinates several repositories and external services, manages the transaction, and emits events. Controllers stay thin and only translate HTTP to and from these calls. The same use case can then be triggered from an HTTP route, a queue consumer or a CLI without duplicating logic.
ts
export class OrderService {
constructor(
private readonly orders: OrderRepository,
private readonly products: ProductRepository,
private readonly payments: PaymentGateway,
private readonly events: EventPublisher,
) {}
async placeOrder(customerId: string, input: CreateOrderInput): Promise<Order> {
const items = await this.products.findMany(input.items.map((i) => i.productId))
if (items.some((p) => !p.inStock)) throw new BusinessError('Some items are out of stock') // (1)
const order = Order.create(customerId, input.items, items) // (2)
await this.payments.authorise(order.id, order.totalPence) // (3)
await this.orders.save(order)
await this.events.publish({ type: 'order.placed', orderId: order.id }) // (4)
return order
}
}- Business rules live here, not in the controller and not in SQL.
- The domain object computes totals and enforces its own invariants.
- External services are called through interfaces, so the service does not know it is Stripe.
- Tell the rest of the system what happened (event-driven architecture).
Layers, top to bottom:
| Layer | Knows about | Example |
|---|---|---|
| Controller | HTTP | createOrderController |
| Service | Use cases, rules, coordination | OrderService.placeOrder |
| Domain | Business objects and their rules | Order.create, order.cancel() |
| Repository | Storage | PgOrderRepository |
6. What is Dependency Injection?
The short answer
Dependency injection means a class or function receives the things it depends on, such as a database pool, a payment client or a logger, from outside, usually through its constructor, instead of creating them itself. new OrderService(orderRepo, paymentGateway) rather than this.payments = new StripeClient() inside the class. The class then depends on an interface, not a concrete implementation, so you can swap Stripe for another provider, or a fake, by passing something different. In Node, plain constructor injection with one "composition root" that wires everything up is usually enough; frameworks like NestJS add a container that does the wiring.
ts
// without DI: hidden, hard-wired dependencies
class OrderService {
private payments = new StripeGateway(process.env.STRIPE_KEY!)
private db = new Pool({ connectionString: process.env.DATABASE_URL })
}
// with DI: dependencies are passed in
class OrderService {
constructor(private readonly orders: OrderRepository, private readonly payments: PaymentGateway) {}
}
// composition root: the one place that knows the concrete classes
const pool = new Pool({ connectionString: config.DATABASE_URL })
const orderService = new OrderService(new PgOrderRepository(pool), new StripeGateway(config.STRIPE_SECRET_KEY)) // (1)
app.post('/orders', makeCreateOrderController(orderService)) // (2)- All the wiring happens once, at startup, in one file.
- The controller also receives its service, so nothing below the composition root ever calls
newon infrastructure.
| Benefit | Why |
|---|---|
| Swappable implementations | Depend on PaymentGateway, not on Stripe |
| Visible dependencies | The constructor lists everything the class needs |
| One place for configuration | Secrets and URLs are read once, at the root |
| Easy substitution | Pass an in-memory repository to run the service in isolation |
DI versus the dependency inversion principle. Dependency inversion, the D in SOLID, says high-level code should depend on abstractions, not on low-level details. Dependency injection is the technique that makes that practical.
7. What is Clean Architecture?
The short answer
Clean Architecture, described by Robert C. Martin, organises code in concentric layers with one rule: dependencies point inward. At the centre are entities, the core business rules. Around them are use cases, the application's operations. Then interface adapters, such as controllers, presenters and repository implementations. On the outside are frameworks and drivers, such as Express, PostgreSQL and Stripe. Inner layers never import outer ones; they define interfaces that outer layers implement. The business logic therefore does not depend on the web framework or the database, and can outlive both.
A folder layout that follows it:
text
src/
domain/ order.ts, money.ts entities: no imports from outside domain
application/ place-order.ts, ports.ts use cases and the interfaces they need
adapters/ http/orders-controller.ts translate HTTP to use cases
db/pg-order-repository.ts implement ports.ts with PostgreSQL
main.ts composition root: wires everythingThe honest trade-off. Clean Architecture adds layers and interfaces. For a small CRUD service it is too much. It pays off when the business rules are complex and long-lived, and the tools around them will change.
8. What is Hexagonal Architecture?
The short answer
Hexagonal architecture, also called ports and adapters, by Alistair Cockburn, puts the application core in the middle and lets it talk to the outside world only through ports: interfaces the core defines, such as PaymentGateway or OrderRepository. Adapters plug into those ports: an Express controller or a queue consumer drives the app from one side; a PostgreSQL repository or a Stripe client is driven by it on the other. The core never knows which adapter is plugged in. It is the same dependency rule as Clean Architecture, explained with a simpler picture.
ts
// port, owned by the core
export interface PaymentGateway { authorise(orderId: string, amountPence: number): Promise<{ authId: string }> }
// adapter, on the outside
export class StripeGateway implements PaymentGateway {
constructor(private readonly stripe: Stripe) {}
async authorise(orderId: string, amountPence: number) {
const pi = await this.stripe.paymentIntents.create({ amount: amountPence, currency: 'gbp', capture_method: 'manual', metadata: { orderId } })
return { authId: pi.id }
}
}| Clean Architecture | Hexagonal | |
|---|---|---|
| Picture | Concentric rings | A core with ports on its edges |
| Rule | Dependencies point inward | The core defines ports; adapters implement them |
| Emphasis | Layers of policy | Inside versus outside |
| In practice | Same code structure | Same code structure |