Skip to content

Interview PrepStructure · Core

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.

modular monolith: one deployorders modulepayments moduleusers modulecatalogue modulefunction calls inside one processone database, schema per modulemicroservices: four deploysorders servicepayments serviceusers servicecatalogue servicenetwork calls and eventsDBDBDBDB
Same boundaries, different deployment. A modular monolith already separates the business areas, but they run in one process and call each other directly. Microservices put each area in its own process with its own database, so a call between them crosses the network.
MonolithMicroservices
DeployOne unitEach service separately
DataOne databaseOne database per service
Calls between partsFunction calls: fast, reliableNetwork calls: slower, can fail
Transactions across partsOne database transactionSagas and eventual consistency (sagas)
ScalingScale the whole appScale each service
Team independenceLow, shared releaseHigh, own release
DebuggingOne log, one stack traceDistributed 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.

AdvantageThe cost that comes with it
Independent deploysVersioned APIs, backward compatibility between services
Independent scalingMore infrastructure, service discovery, load balancing
Fault isolationOnly if you build timeouts, circuit breakers and fallbacks (resilience)
Team autonomyCoordination through contracts instead of code review
Technology choiceMore languages and stacks to support
Smaller codebasesLogic and data split across the network

Signs you are ready to split a service out:

  1. Several teams keep blocking each other's releases in one codebase.
  2. One part has very different scaling needs, such as image processing.
  3. One part needs a different reliability or security boundary, such as payments.
  4. 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) })
  1. Validate the input at the edge.
  2. Hand off to the model side, here a service (question 5).
  3. The view decides the response shape, so internal fields never leak.
RoleIn an Express APIMust not
ModelDomain objects, services, repositoriesKnow about req and res
ViewResponse mappers, templatesContain business rules
ControllerRoute handlersRun 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])
  }
}
  1. The interface speaks the business's language, "open orders for a customer", not SQL.
  2. Map rows to domain objects in one place, so customer_id columns 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
  }
}
  1. Business rules live here, not in the controller and not in SQL.
  2. The domain object computes totals and enforces its own invariants.
  3. External services are called through interfaces, so the service does not know it is Stripe.
  4. Tell the rest of the system what happened (event-driven architecture).

Layers, top to bottom:

LayerKnows aboutExample
ControllerHTTPcreateOrderController
ServiceUse cases, rules, coordinationOrderService.placeOrder
DomainBusiness objects and their rulesOrder.create, order.cancel()
RepositoryStoragePgOrderRepository

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)
  1. All the wiring happens once, at startup, in one file.
  2. The controller also receives its service, so nothing below the composition root ever calls new on infrastructure.
BenefitWhy
Swappable implementationsDepend on PaymentGateway, not on Stripe
Visible dependenciesThe constructor lists everything the class needs
One place for configurationSecrets and URLs are read once, at the root
Easy substitutionPass 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.

entitiesuse casesadaptersframeworks, driversdependencies point inwardentities: Order, its rulesuse cases: PlaceOrder, RefundOrderadapters: controllers, PgOrderRepositoryframeworks: Express, PostgreSQL, Stripe
The business rules sit in the middle, untouched by tools. Each ring may use the rings inside it, never the ones outside. The database and the web framework are details on the edge, so replacing them does not touch the use cases.

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 everything

The 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.

application coreuse cases + domainknows only portsHTTP controllerqueue consumerPg repositoryStripe clientdriving sidedriven side
Plugs on both sides. On the left, things that start work, such as an HTTP request or a queue message, call into the core. On the right, things the core needs, such as storage and payments, are reached through interfaces the core owns. Any adapter can be swapped without touching the middle.
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 ArchitectureHexagonal
PictureConcentric ringsA core with ports on its edges
RuleDependencies point inwardThe core defines ports; adapters implement them
EmphasisLayers of policyInside versus outside
In practiceSame code structureSame code structure

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Architecture & Distributed Systems
Structure
Data across services
Resilience
Communication
Security between services
Algorithms
Other topics
Nothing picked yet