name: design-backend-project-structure description: Use when starting a backend service or API (Node/NestJS, Python/FastAPI/Django, Go, Java/Spring, .NET, Rails), or when an existing backend has become hard to navigate — business logic in controllers, giant services/ or utils/ folders, config and migrations scattered, unclear entry points. source: 'Go Team, "Organizing a Go module", 2023; Spring, "Spring Modulith Reference Documentation"; NestJS Documentation, "Modules"; Django Documentation, "Applications"; Wiggins, "The Twelve-Factor App", 2011; Martin, "Clean Architecture", 2017; Bogard, "Vertical Slice Architecture", 2018' tags: [project-structure, backend, api, service-layout, modular-monolith, maintainability] related: [apply-package-by-feature, apply-hexagonal-architecture, apply-vertical-slice-architecture, apply-module-boundary-enforcement, design-repository-layout, write-database-migration, apply-twelve-factor-app]
Design Backend Project Structure
Lay out a backend as a modular monolith by default: feature modules at the top level, a thin layer structure inside each module, explicit entry points, and infrastructure (config, migrations, deployment) in predictable places.
Why This Is Best Practice
Adopted by:
- Shopify's and GitHub's componentized Rails monoliths.
- Spring Modulith, NestJS modules, and Django apps.
- The Go team's official module-layout guide.
Impact:
- Fowler's "MonolithFirst" (2015) observes that almost all successful microservice systems started as monoliths that were split later, and that systems built as microservices from scratch often ran into serious trouble.
- A well-modularized monolith keeps that option open while avoiding distributed-systems cost.
- Accelerate (2018) links loosely coupled architecture to higher delivery performance.
Why best:
- Structure should optimize for the most common change: adding or modifying a feature.
- Feature modules keep those changes local.
- A light internal layering (API → application → domain → infrastructure) keeps business logic testable.
- Standard places for config, migrations, and entry points make the service operable by anyone.
Sources: Go Team (2023), "Organizing a Go module". Spring Modulith docs. NestJS docs, "Modules". Django docs, "Applications". Fowler, M. (2015), "MonolithFirst". Wiggins (2011), Twelve-Factor App. Martin (2017), Clean Architecture.
Steps
Pick an architecture style per complexity:
Situation Style CRUD-heavy, simple rules Feature modules with simple layers, or vertical slices ( apply-vertical-slice-architecture)Rich domain, many integrations, long-lived Feature modules with hexagonal cores ( apply-hexagonal-architecture)Multiple teams, one deployable Modular monolith with enforced boundaries ( apply-module-boundary-enforcement)Record the choice in an ADR.
Organize the top level by feature module (
apply-package-by-feature):src/ main.ts | main.go | app.py # entry point / composition root modules/ orders/ api/ # routes/controllers, request/response DTOs, validation application/ # use cases / services, ports domain/ # entities, value objects, domain errors infrastructure/ # repositories, external clients, mappers orders.module.ts # wiring (or __init__.py / module registration) tests/ or *_test.* colocated billing/ shared/ # logging, error types, auth middleware, db client, clock config/ # typed config loading and validation migrations/ # versioned schema migrations (Flyway, Alembic, golang-migrate, Prisma) tests/ # e2e / contract tests spanning modules deploy/ # Dockerfile, k8s/Helm, compose for local depsApply ecosystem conventions:
- Go:
cmd/<binary>/main.go(or rootmain.gofor one binary). Private code ininternal/<module>/. Avoidpkg/unless you're deliberately publishing packages. No globalmodels/orutils/. - Python: src layout (
src/<pkg>/) withpyproject.toml. FastAPI routers per module. Django: one app per bounded capability, not one giant app. - Java/Kotlin (Spring): a base package per module (
com.acme.orders) with package-private internals, verified by Spring Modulith or ArchUnit. Maven/Gradle standard layout (src/main/java,src/test/java). - Node (NestJS/Express): one Nest module per feature. Keep
controllers/andservices/inside the feature folder. - .NET: a project per module (
Orders.Api,Orders.Core,Orders.Infrastructure) or feature folders with vertical slices.
- Go:
Keep controllers thin. HTTP handlers parse and validate input, call one application service or use case, and map the result to a response. No business rules or SQL in handlers.
Centralize configuration. Load from the environment into one typed, validated config object at startup (pydantic-settings,
envconfig, Spring@ConfigurationProperties, zod). Fail fast if keys are missing. Never readprocess.envoros.environdeep inside business code.Version the database schema in the repo. Use sequential, immutable migrations in
migrations/, run by CI/CD (seewrite-database-migration). Never edit a migration that has already been applied.Make cross-cutting concerns explicit: a single error-handling middleware with domain errors mapped to HTTP status codes, structured logging with request IDs, auth as middleware, and health/readiness endpoints in a
healthmodule orshared/.Structure tests to mirror the code:
- unit tests colocated with modules
- integration tests for infrastructure adapters (Testcontainers)
- a few e2e/contract tests in root
tests/
Enforce module boundaries once more than one module exists, and keep the API contract (OpenAPI/proto) versioned in the repo (
api/orproto/).
Rules
- Top level by feature, layers inside the feature.
- Entry points and wiring live in one obvious place.
- Business logic never lives in controllers, ORM models, or migrations.
- Config is typed, validated at startup, and supplied by the environment.
- Split into microservices only when a module needs independent scaling, deployment, or team ownership, and its boundary has proven stable.
Common Mistakes
- Global
models/,services/,utils/. Every feature touches every folder, and services become god classes. - Premature microservices. Distributed transactions, network failures, and deployment overhead before the domain is understood.
- Fat ORM models. Persistence, validation, and business rules tangled in one class.
- Scattered config. Env vars read across dozens of files, and missing keys only discovered in production.
- One shared database schema accessed by every module. Give each module ownership of its tables, even within one database.
Examples
FastAPI service: src/shop/main.py creates the app and includes modules/orders/api.py and modules/catalog/api.py routers. Each module has service.py, repository.py, models.py (domain), and schemas.py (pydantic DTOs). src/shop/config.py holds Settings(BaseSettings). Alembic lives in migrations/. tests/e2e/ uses httpx against Testcontainers Postgres.
Go API: cmd/api/main.go wires internal/orders, internal/billing, and internal/platform/{db,log,config}. Each feature package exposes a Service and an HTTP Handler and hides its repository. migrations/ holds golang-migrate files.
When NOT to Use
- Serverless functions with one handler. A single file plus a shared lib is fine.
- Opinionated frameworks with mandatory layouts (Rails, Laravel). Follow the framework, and add feature grouping through namespaces, engines, or packs where needed.