Nguyen Le Phong

Foundations of Software ArchitecturePart 4 of 15

Group Code by Feature or by Layer? Let the Next Change Decide

Your top-level folders decide how many places one change touches.

Product wants refunds. Fair enough, it's one feature. You open the repo and start adding files: a route in controllers/, the logic in services/, a query in repositories/, a new field in models/. That's four folders for one idea, and the rest of the team is editing every one of them this sprint too.

Nobody really decided this. It came from the first folder someone created on day one, probably copied from a framework tutorial. This post compares the three common ways to group code (by layer, by feature, by business domain), what each one costs as the codebase grows, and how to keep the boundaries real once several teams share the repo.

Three engineers around a table move physical blocks around while they argue about which parts of a codebase belong together.
Folder structure gets concrete fast once a team has to point at the pieces that change together.

Folders decide where a change lands

It's tempting to treat folder layout as tidiness, something you argue about once and forget. In practice it decides three things you feel every week:

  • How far one change spreads. If code that changes together lives in different folders, every feature becomes a trip across the tree, and every PR touches files other people are also editing.
  • How fast people find things. A new teammate asks "where's the billing code?" One folder is an answer. "Some of it's in services/, some in models/, and check utils too" is a scavenger hunt.
  • How safely you can delete. When a feature gets retired, can you remove it in one go, or does half of it stay behind because nobody's sure which helpers it owned?
Think of a city map

A city map groups places by neighborhood. Nobody prints one with every bakery on page one and every school on page two, even though that's technically organized. Grouping files by type (all controllers here, all models there) is the bakery-page map. Grouping by feature is the neighborhood map, the one you can actually use to get somewhere.

Team shape pulls on this as well. In 1968 Melvin Conway wrote that organizations design systems that copy their own communication structure (How Do Committees Invent?; Martin Fowler has a readable modern summary). If your teams are split by product area, say a payments squad and an orders squad, folders split the same way give each squad a place it owns. Folders split by layer mean every squad edits every folder.

By layer: the tutorial default

Group files by technical role and a typical Node or Spring project looks like this:

src/
β”œβ”€ controllers/
β”‚  β”œβ”€ OrderController.ts
β”‚  β”œβ”€ UserController.ts
β”‚  └─ BillingController.ts
β”œβ”€ services/
β”‚  β”œβ”€ OrderService.ts
β”‚  β”œβ”€ UserService.ts
β”‚  └─ BillingService.ts
β”œβ”€ repositories/
β”‚  β”œβ”€ OrderRepository.ts
β”‚  β”œβ”€ UserRepository.ts
β”‚  └─ BillingRepository.ts
└─ models/
   β”œβ”€ Order.ts
   β”œβ”€ User.ts
   └─ Invoice.ts
Grouped by layer: each technical role gets a top-level folder, so every new feature adds files to all four.

Many framework starters and tutorials point you here, and it's a fair place to start. Everyone recognizes it on day one, and while the app has a handful of features each folder is small enough to scan.

It works well when:

  • The app is small and has few features. Any structure reads fine at that size.
  • The whole team works across the whole app, so nobody needs a part of the tree to call their own.
  • You're building a prototype or an internal tool, and getting it running beats planning for the next two years.

It starts to hurt when:

  • One feature is spread over every folder. Refunds is one thing in everyone's head and four folders in the repo.
  • Deleting gets nervous. Which files in services/ belong to billing and which to orders? The folder name won't tell you, so dead code tends to stay.
  • Parallel work collides. Two people building unrelated features still edit the same folders and, sooner or later, the same service file.
The junk drawer

Nobody can give you an exact feature count where this breaks, and you'll feel it long before you can measure it. The usual signs: services/ holds dozens of files, nobody owns the folder as a whole, and reviewers keep seeing files they've never opened before.

By feature: one change, one folder

Group files by the part of the product they serve. The layers don't go away. Controller, service and repository still exist, they live inside each feature folder:

src/
β”œβ”€ orders/
β”‚  β”œβ”€ OrderController.ts
β”‚  β”œβ”€ OrderService.ts
β”‚  β”œβ”€ OrderRepository.ts
β”‚  └─ Order.ts
β”œβ”€ billing/
β”‚  β”œβ”€ BillingController.ts
β”‚  β”œβ”€ BillingService.ts
β”‚  β”œβ”€ BillingRepository.ts
β”‚  └─ Invoice.ts
β”œβ”€ auth/
β”‚  β”œβ”€ AuthController.ts
β”‚  β”œβ”€ AuthService.ts
β”‚  └─ User.ts
└─ shared/
   β”œβ”€ database.ts
   β”œβ”€ logger.ts
   └─ Money.ts
Grouped by feature: each product area owns a folder. Refunds goes inside billing/ and the other folders stay put.

What you get:

  • Changes stay local. Refunds means new files in billing/ and nothing else, so the PR is easy to review.
  • Deleting is honest. Remove the folder, and the compiler or your editor points at every import that still reaches into it.
  • Ownership is obvious. Payments owns billing/, identity owns auth/, and a CODEOWNERS file can say so in one line each.
  • Onboarding gets narrower. Someone starting on orders reads orders/ first and leaves the rest for later.

What needs care:

  • Shared code needs a home. Orders and billing both use Money, so it can't live in either. It goes to shared/, and if nobody owns that folder it becomes the next junk drawer.
  • Features can still reach into each other. If orders/OrderService.ts imports something deep inside billing/, the folders look separate while the code is tangled. You'll want a rule that catches this, and there's one below.

What lights up when you ship refunds

The fastest way to see the difference is to count the folders one feature touches.

Adding refunds. By layer, all four layer folders change. By feature, only the billing folder changes. BY LAYER: adding refunds controllers/ ← changed services/ ← changed repositories/ ← changed models/ ← changed 4 folders changed change spreads wide BY FEATURE: adding refunds orders/ billing/ ← changed auth/ shared/ 1 folder changed change stays local
The same refunds feature in two layouts. By layer (left), all four folders change. By feature (right), only billing/ does and the rest of the code stays where it was.

Those four lit boxes turn into real costs: a PR that's harder to review, more merge conflicts with teammates, and a git log where one feature's history is smeared across the whole tree. When the change sits in one folder, the review, the history and the rollback sit there too.

Screaming Architecture: the top level should say what the system does

In 2011 Robert C. Martin (Uncle Bob) wrote Screaming Architecture. Look at the blueprint of a house, he says, and it screams "house". Look at a library's and it screams "library". So what do your top-level folders scream? Health care, accounting, inventory? Or Rails, Spring, ASP.NET? His line that stuck with a lot of people: "Frameworks are tools to be used, not architectures to be conformed to."

Grouping by domain takes by-feature one step further. The folder names come from words the business already uses (Domain-Driven Design calls this the ubiquitous language), so a product manager can read them too:

// Says "online shop"
src/
β”œβ”€ catalog/          // products and what we sell
β”œβ”€ ordering/         // placing and tracking orders
β”œβ”€ fulfillment/      // picking, packing, shipping
β”œβ”€ payments/         // charges, refunds, invoices
└─ identity/         // accounts, login, permissions

// Says "some MVC framework"
src/
β”œβ”€ controllers/      // HTTP plumbing
β”œβ”€ models/           // ORM classes
β”œβ”€ views/            // templates
└─ services/         // everything else

What goes inside each domain folder is up to the team. The top level is the part that matters: a new developer, or someone from the business side, should be able to read it and tell what the system does before they know how it's built.

Side by side

Here's how the three compare on questions that come up every week:

Question By layer By feature By domain (screaming)
Where's the billing code? Spread across every layer folder In billing/ In payments/, named the way the business says it
Folders one feature change touches Usually every layer Mostly one Mostly one
Deleting a feature Hunt for its files in each layer Delete the folder, fix the imports the compiler flags Same as by feature
Who owns what Hard to say, every team edits every folder One team per folder One team per business area
How it usually goes wrong Layer folders turn into junk drawers shared/ grows with no owner Domain lines drawn too early, in the wrong place
A team moves colored tokens between a board split by layer and a board split by business area during a design discussion.
The useful question is which grouping keeps one product change in one place a teammate can understand.

The mix many teams end up with

Martin Fowler lands in the same spot. Splitting code into presentation, domain and data is useful, he writes, but "it should only be applied at a relatively small granularity." As an app grows, "you should split your top level into domain oriented modules which are internally layered" (PresentationDomainDataLayering). In folder terms: features or domains on top, small layers inside each one.

Hybrid layout: domain or feature folders at the top, small technical layers inside each one. HYBRID: domains on top, layers inside src/ orders/ billing/ shared/ controller.ts service.ts repository.ts Order.ts controller.ts service.ts repository.ts Invoice.ts Money.ts logger.ts database.ts
Domains or features at the top, small technical layers inside each folder. The layers are all still there. They're no longer the first thing you see.

Why this mix holds up:

  • The top level tells you it's a shop with orders and billing before you see any framework.
  • Each feature keeps its own code, so a billing change stays in billing/.
  • Anyone used to MVC or Clean Architecture still finds controller, service and repository files where they expect them, one level down.
  • shared/ holds what's genuinely cross-cutting: a Money value object, the logger, the database client. Everything else stays inside a feature.
Keeping shared/ small

Call it shared/, common/ or lib/, the name barely matters. Treat it like a small internal library with an owner. One easy test: if a file in shared/ keeps changing in the same PRs as one particular feature, it belongs inside that feature.

When folders aren't enough: let a tool hold the line

Folders are a convention, and anyone in a hurry can type import { applyDiscount } from '../../billing/internal/discounts'. Once a few teams share the repo, you want a machine to catch that. Start by giving each feature a single public entry point:

// src/billing/index.ts
export { createRefund } from './refunds/createRefund';
export type { Invoice } from './Invoice';
One public entry point per feature. Anything not exported here is billing's private business.

Then pick a tool that checks it:

  • ESLint's import/no-restricted-paths rule blocks imports from one folder into another, with exceptions for specific files. If you already run ESLint, it's the smallest step.
  • Nx module boundary rules tag each project (for example scope:orders or scope:shared) and fail lint when a project depends on a tag it isn't allowed to.
  • NestJS modules encapsulate their providers: another module can only inject what a module explicitly exports.
  • For Rails, Shopify built Packwerk, a static analysis tool that reports dependency and privacy violations between packages.
// .eslintrc.cjs
module.exports = {
  plugins: ['import'],
  rules: {
    'import/no-restricted-paths': ['error', {
      zones: [{
        target: './src/orders',
        from: './src/billing',
        except: ['./index.ts'],
        message: 'Import billing through src/billing/index.ts',
      }],
    }],
  },
};
Orders can only import billing through billing/index.ts. Anything deeper fails lint in CI.

Shopify shows what a late move looks like. Their core Rails app, worked on by more than a thousand developers over more than a decade, was laid out like a typical Rails app: models, views, controllers. In early 2017 a small team started regrouping it by real-world concepts such as orders, shipping, inventory and billing. They listed about 6,000 Ruby classes, labeled each one with its component, and then moved every file in one big pull request generated by scripts (Deconstructing the Monolith). Their own advice is worth keeping: re-architect as late as you can, and treat features getting slower to ship as the sign that it's time.

You don't need a monorepo with one package per domain to get these benefits. Plenty of teams run a single package with feature folders and one boundary rule for years. Split into packages when cross-team coupling actually starts to hurt.

A rough guide by team size

Treat these as rules of thumb. The shape of your product matters more than headcount.

Stage Structure to reach for Why What to do now
Solo or pre-launch By layer, or shallow feature folders A few features and a lot of unknowns. Keep it simple. The framework default is fine. Leave yourself a note to revisit when folders get crowded.
One team (roughly 5 to 20) Feature folders plus a small shared/ Features keep arriving and people start working in parallel. Move to feature folders while the move is still a short, boring PR.
Several teams (roughly 20 to 100) Domains on top, layers inside, plus a boundary lint rule Teams own areas, and accidental cross-team imports start costing real time. Add CODEOWNERS and one boundary rule in CI before adding more structure.
Many teams (100+) Domain packages in a monorepo, or separate services per bounded context Teams need independent builds, releases and versioned interfaces. Shopify kept one Rails app and checked package boundaries with Packwerk. Splitting into services is the other route, and it has its own bill.
Three engineers review architecture boards together while choosing a structure for the team they're growing into.
Pick the structure whose boundaries still hold when new people, features and dependencies show up.
The common mistake

Starting by layer is rarely the problem. Staying there after it hurts usually is. When reviewers start asking "wait, what else does this service touch?", put the move on the calendar. That PR only gets bigger.

Try this week

  • Pick your last three feature PRs and count how many top-level folders each one touched.
  • Ask the newest person on the team to find the billing code without help, and watch where they look first.
  • Open shared/ (or utils/) and move one file that only one feature uses back into that feature.
  • Give your busiest feature folder an index.ts and add a lint rule that forces other features through it.

If you want to go a step further and organize each feature around individual requests, read Layered vs. Vertical Slice Architecture. And when one service stops being enough, the next stop is Monolith to Microservices.

What did you think?

Frequently asked questions

Should I organize code by feature or by layer?
For a small app with a few features, grouping by layer (controllers, services, models) is fine. Once features pile up and people work in parallel, put feature or domain folders at the top and keep small layers inside each one. Martin Fowler recommends exactly that shape as an application grows.
What is Screaming Architecture?
It's Robert C. Martin's 2011 idea that your top-level folders should tell a reader what the system does, such as orders, billing or inventory, before they tell them which framework it uses. Framework folders like controllers and models move one level down.
Where does shared code go in a feature-based structure?
In a small shared folder with a clear owner, for things that are genuinely cross-cutting: a Money value object, the logger, the database client. If a shared file keeps changing in the same pull requests as one feature, move it into that feature.
How do I stop features importing each other's internals?
Give each feature one public index file, then enforce it with a tool: ESLint's import/no-restricted-paths rule, Nx module boundary tags, NestJS module exports, or Packwerk for Rails. Run the check in CI so a deep import fails the build.