Nguyen Le Phong

Foundations of Software ArchitecturePart 13 of 15

Layered or Vertical Slices? Follow Where Your Changes Land

Layered code groups files by kind; vertical slices group them by request.

Someone opens a PR to add one small rule: refunds over $500 need a second approver. The rule fits in three lines. The diff touches seven files: a controller, a service, a repository, a DTO, a mapper, a validator and a test in a folder on the other side of the repo. Plus one shared helper that three other features also call, which nobody wants to be the one to change.

That gap between how small a change is and how many places it lands is what this post is about. Layered architecture and vertical slice architecture are two answers to one question: what should sit next to what? If you're mostly deciding how to name your top-level folders, Group Code by Feature or by Layer? covers that. Here we go one level deeper, into how each style shapes the code inside, where coupling ends up and how to move from one to the other without a big rewrite.

Hands arrange route notes, validation cards, a use-case diagram and data-access sketches together on one small workbench.
A slice keeps everything one change needs on the same bench: the route, the rules, the data access and the tests.

Layered: group code by what kind of code it is

The classic split is presentation, domain and data. Martin Fowler's note on presentation-domain-data layering explains why it caught on: you can think about each topic on its own, put several UIs on the same domain logic, cope with a database change, and the boundaries give you natural seams for testing. Most framework tutorials start here, which is why controllers, services and repositories feel like the default.

src/
  controllers/   RefundController.ts  InvoiceController.ts  ...
  services/      RefundService.ts     InvoiceService.ts     ...
  repositories/  RefundRepository.ts  InvoiceRepository.ts ...
  validators/    RefundValidator.ts   InvoiceValidator.ts   ...

That structure is honestly fine for a small app. New people know where to look, conventions are obvious, and when everyone works across the whole codebase anyway, grouping by technical role is enough.

The cost shows up slowly, somewhere around the tenth or twentieth feature. A change that should be local starts touching every layer. Reviewers jump between folders to follow one behavior. Shared services grow methods that only one caller uses. Deleting an old feature turns into a search through every folder, because its pieces sit next to everything else's. Fowler makes the same point about scale: for larger systems it's "usually not best to use presentation-domain-data as the higher level of modules", and once a layer gets too big you should split the top level into domain-oriented modules that are layered inside.

Vertical slice: group code by the request it serves

Jimmy Bogard described vertical slice architecture in 2018. Each slice is built around one request (a command or a query) and holds everything that request needs, from the endpoint down to the database. His rule of thumb fits on a sticky note: "Minimize coupling between slices, and maximize coupling in a slice."

src/
  features/
    approve-refund/
      approve-refund.ts        // endpoint + handler
      approve-refund.test.ts
    create-invoice/
      create-invoice.ts
      create-invoice.test.ts
  shared/
    db.ts                      // only what has proven to be common

The folder list reads like a list of things the product does. Each slice can be as simple as it needs to be. Bogard suggests starting with a Transaction Script (Fowler's name for a procedure that handles one request from start to finish) and refactoring toward a richer domain model only when the code starts to smell. A simple approval can stay this small:

// features/approve-refund/approve-refund.ts
import type { Pool } from 'pg'

export type ApproveRefund = { refundId: string; approverId: string }

export async function approveRefund(db: Pool, cmd: ApproveRefund): Promise<boolean> {
  const result = await db.query(
    `UPDATE refunds
        SET status = 'approved', approved_by = $2, approved_at = now()
      WHERE id = $1 AND status = 'pending'`,
    [cmd.refundId, cmd.approverId],
  )
  return result.rowCount === 1
}

No service, no repository interface, no mapper. When the "over $500 needs two approvers" rule arrives, it goes into this file, and the PR touches one folder. If the refund rules keep growing (limits per country, approval chains, audit trails), that's the signal to pull them into a small domain object that lives inside the slice. Layers still exist in a vertical slice codebase. They just sit inside each feature, and each feature decides how many it needs.

Bogard also notes a nice side effect: new features mostly add code instead of editing shared code, so a change in one slice is less likely to break another.

Side by side

LayeredVertical slice
The folders answer"What kind of code is this?""Which feature is this part of?"
A typical feature change touchesOne file per layerMostly one folder
Shared codeA lot, by design (services, repositories)Little, added only when it's earned
Complexity per featureSame shape for every featureEach slice picks what it needs
Easy for newcomersYes, it matches most tutorialsYes once they know the conventions, confusing without them
Main riskSmall changes spread across the codebaseSlices drift apart, duplication piles up

Sharing code without building a new tangle

Vertical slices come with a discipline cost. Without agreements on naming, shared utilities and boundaries, a codebase can turn into dozens of small islands that each solve the same problem slightly differently.

The rule that works well here comes from Sandi Metz: "duplication is far cheaper than the wrong abstraction." Two slices with a similar-looking mapper don't have to share one. Share code when the duplicates keep changing together for the same reason, which means they really are the same idea. If they only look alike, leave them alone. And when a shared helper has grown a pile of flags to serve every caller, Metz's advice is to inline it back into the callers and start over.

Two engineers put a few shared building blocks on one shelf while most feature trays stay separate, next to a rainy city window.
Only a few pieces make it to the shared shelf. Most code stays in its feature tray until it has proven it's truly common.

A few habits keep a sliced codebase healthy:

  • Slices don't import from each other. If one needs another's data, it reads it through the database or a small published function and leaves the other slice's internals alone.
  • Keep shared/ deliberately boring: database access, auth, logging, money formatting. If something in there knows about refunds, it probably belongs in a slice.
  • Name slices after what users and the business say: approve-refund, change-email-address. Avoid technical names like refund-manager.
  • Splitting by request lines up nicely with separating commands from queries. If that interests you, the CQRS post goes further.

Which one fits your team

Look at how work usually arrives. If most tickets are product capabilities ("let support approve refunds", "add bulk invoice export"), vertical slices make the code follow the work. If most changes are cross-cutting technical upgrades (swap the ORM, add caching everywhere), layers can still feel natural, because the change really is "one layer, every feature."

Bogard is upfront about one requirement: the approach assumes your team can spot code smells and knows when to refactor. Without that, slices drift into copy-paste and nobody notices until it's painful. A team that's still building those habits may do better with a well-kept layered structure plus some coaching.

Many teams end up in between: feature folders at the top, a few small layers inside the features that need them, and a small shared folder for things that have truly become common. That's close to what Fowler recommends for larger systems anyway.

Moving over without a big rewrite

You don't need a migration project. Build the next new feature as a slice. Keep its public surface small, and move only the code that changes together with it. When you have to make a real change to an old layered feature, pull that feature into its own folder as part of the same PR. After a few features, compare: are the PRs smaller, are the reviews easier, did anything break somewhere unexpected? Let that evidence decide the next step, more than whoever argued loudest in the architecture meeting.

A half-built prototype sits on a lab bench next to a laptop and adapters, every part still easy to trace.
Move one feature at a time, while each part is still easy to see and trace, before it joins the rest of the system.

Try this week

  • Pick your last three feature PRs and count how many folders each one touched.
  • Find one shared service method with a single caller and move it into that caller's feature.
  • Build the next small feature as a slice: endpoint, logic, data access and test in one folder.
  • Look for a shared helper with boolean flags for different callers, and try inlining it back.
  • Write down your team's rule for when code moves into shared/, so the next person doesn't have to guess.
What did you think?

Frequently asked questions

What is vertical slice architecture?
A style Jimmy Bogard described in 2018 where code is organized around individual requests (commands and queries). Each slice holds everything one request needs, from the endpoint to the database, and the guiding rule is to minimize coupling between slices and maximize coupling inside a slice.
Is layered architecture bad?
No. Splitting presentation, domain and data works well for small apps and is easy for newcomers to follow. Martin Fowler's advice is that once a layer grows too big, larger systems should split the top level into domain-oriented modules that are layered inside.
Do vertical slices still have layers?
Yes, they just live inside each feature. A simple slice can be one Transaction Script; a slice with growing rules can pull them into a small domain object of its own. Each feature decides how many layers it needs.
How do I avoid duplicated code across slices?
Accept some duplication at first. Sandi Metz's rule is that duplication is far cheaper than the wrong abstraction. Share code only when copies keep changing together for the same reason, keep the shared folder small and boring, and don't let slices import from each other.
How do I migrate from layers to vertical slices?
Build the next new feature as a slice, and move an old feature into its own folder only when you have a real change to make to it. Compare PR size and review effort after a few features before going further.