Polski

Article · Layered Architecture · Hexagonal Architecture

Layered architecture: presentation, logic, data – and where it breaks

The oldest and most popular way of structuring business applications: closed and open layers, layers versus tiers, code in C#, TypeScript, Java, Go and Python, ArchUnit and NetArchTest tests, and the road to the hexagon.

By · · 12 min read

The catering module at Halina's pierogi place – quotes for weddings and first communions – was built the way most courses teach: a controller takes the request, a service calculates the price, a repository reads the menu from the database. This is layered architecture, the default layout of almost every project template. It is simple and readable, but it has one property that comes back like a boomerang after a few years: the business logic depends on the database.

1968
layers in the THE system – Edsger Dijkstra describes a system built of levels
3
classic layers – presentation, domain, data source (Fowler, 2002)
80/20
the sinkhole rule – about 20% of requests may simply pass through the layers (Mark Richards)

Context and forces

Catering has a few rules (at least a week's notice, a discount from a hundred guests), but most of the work is ordinary forms: menu, dates, customer details. The team is mixed – juniors and two seniors – and needs a structure everyone understands from day one.

  • Separation of concerns – HTML and JSON shouldn't mix with SQL and pricing rules.
  • Predictability – everyone knows where to look for validation, where for rules and where for queries.
  • Replaceable layers – a new interface (a mobile app) shouldn't require changes in the logic.
  • Cost – the structure must not cost more than the problem it solves.

Structure

The layers pattern was described, among others, by Buschmann and co-authors in Pattern-Oriented Software Architecture (1996), and Martin Fowler's Patterns of Enterprise Application Architecture (2002) popularised three layers: presentation, domain and data source.

Diagram: Three layers: each depends only on the layer below
LayerResponsibilityShould not
PresentationAccepting the request, format validation, mapping to DTOs, HTTP status codescalculate prices or write SQL
Business logicRules, use cases, transactionsknow HttpContext, req, res
Data accessQueries, object-relational mapping, cachingmake business decisions

Layers versus tiers. A layer is a logical division in the code, a tier is a physical one: a separate process or machine. Three layers can run in a single process, while a three-tier application from the 1990s is a browser, an application server and a database server.

Closed and open layers. In a closed layout, a request passes through every layer in turn. In an open one, selected layers can be skipped – for example, a simple read goes from the controller straight to the repository. Openness speeds up writing but blurs the boundaries, so it's worth limiting it to specific, named cases.

What it looks like in code

Layer layout in five stacks

dotnet/solution-tree.txt
Pierogarnia.Catering.sln
├── Catering.Web/            ← PRESENTATION: controllers, view models, validation of input
├── Catering.Business/       ← BUSINESS: CateringService, pricing rules, DTOs
├── Catering.Data/           ← DATA ACCESS: EF Core DbContext, repositories, entities
└── references: Web → Business → Data   (each layer knows only the one below)
java/package-tree.txt
pl.pierogarnia.catering
├── web/            ← @RestController, request/response records
├── service/        ← @Service, @Transactional, business rules
├── repository/     ← Spring Data JPA interfaces
└── entity/         ← @Entity classes (often shared by service and repository)
node/src-tree.txt
src/
├── controllers/    ← Express routers or NestJS @Controller
├── services/       ← business rules, no req/res objects here
├── repositories/   ← Prisma / TypeORM / Knex queries
└── app.ts
go/module-tree.txt
catering/
├── cmd/catering/main.go
└── internal/
    ├── handler/    ← net/http handlers: decode JSON, call service, encode JSON
    ├── service/    ← business rules
    └── repository/ ← database/sql or sqlc queries
python/package-tree.txt
catering/
├── api/            ← FastAPI routers (presentation)
├── services/       ← business rules
├── repositories/   ← SQLAlchemy queries
└── models.py       ← ORM models

The same use case – a wedding quote – passes through three layers. Notice where the discount rule lives and what the service depends on:

A wedding quote through three layers

Catering.cs
// PRESENTATION – Catering.Web
[ApiController, Route("api/catering")]
public sealed class CateringController(CateringService service) : ControllerBase
{
    [HttpPost("quotes")]
    public async Task<ActionResult<QuoteDto>> Quote(QuoteRequest req, CancellationToken ct) =>
        Ok(await service.Quote(req.Guests, req.EventDate, ct));
}

// BUSINESS – Catering.Business
public sealed class CateringService(ICateringRepository repo, TimeProvider clock)
{
    public async Task<QuoteDto> Quote(int guests, DateOnly date, CancellationToken ct)
    {
        if (date < DateOnly.FromDateTime(clock.GetLocalNow().DateTime.AddDays(7)))
            throw new BusinessRuleException("Weddings need a week's notice.");

        var menu = await repo.GetWeddingMenu(ct);
        var perGuest = menu.Sum(i => i.PiecesPerGuest * i.UnitPrice);
        var discount = guests >= 100 ? 0.10m : 0m;                 // the business rule lives here
        return new QuoteDto(guests, Math.Round(guests * perGuest * (1 - discount), 2));
    }
}

// DATA ACCESS – Catering.Data (the interface is here too: Business references Data)
public interface ICateringRepository { Task<IReadOnlyList<MenuItem>> GetWeddingMenu(CancellationToken ct); }

public sealed class CateringRepository(CateringDb db) : ICateringRepository
{
    public async Task<IReadOnlyList<MenuItem>> GetWeddingMenu(CancellationToken ct) =>
        await db.MenuItems.Where(m => m.Wedding).ToListAsync(ct);
}
catering.ts
// PRESENTATION – controllers/catering.controller.ts
router.post("/api/catering/quotes", async (req, res, next) => {
  try {
    const { guests, eventDate } = req.body as { guests: number; eventDate: string };
    res.json(await cateringService.quote(guests, new Date(eventDate)));
  } catch (err) {
    next(err); // error middleware turns BusinessRuleError into 422
  }
});

// BUSINESS – services/catering.service.ts
export const cateringService = {
  async quote(guests: number, eventDate: Date): Promise<Quote> {
    const weekAhead = Date.now() + 7 * 24 * 3600 * 1000;
    if (eventDate.getTime() < weekAhead) throw new BusinessRuleError("Weddings need a week's notice.");

    const menu = await cateringRepository.weddingMenu();
    const perGuest = menu.reduce((sum, i) => sum + i.piecesPerGuest * i.unitPrice, 0);
    const discount = guests >= 100 ? 0.1 : 0; // the business rule lives here
    return { guests, total: Math.round(guests * perGuest * (1 - discount) * 100) / 100 };
  },
};

// DATA ACCESS – repositories/catering.repository.ts
export const cateringRepository = {
  weddingMenu: () => prisma.menuItem.findMany({ where: { wedding: true } }),
};
Catering.java
// PRESENTATION – web/CateringController.java
@RestController
@RequestMapping("/api/catering")
class CateringController {
    private final CateringService service;
    CateringController(CateringService service) { this.service = service; }

    @PostMapping("/quotes")
    QuoteDto quote(@RequestBody QuoteRequest req) { return service.quote(req.guests(), req.eventDate()); }
}

// BUSINESS – service/CateringService.java
@Service
class CateringService {
    private final MenuItemRepository repo;
    private final Clock clock;
    CateringService(MenuItemRepository repo, Clock clock) { this.repo = repo; this.clock = clock; }

    QuoteDto quote(int guests, LocalDate date) {
        if (date.isBefore(LocalDate.now(clock).plusDays(7)))
            throw new BusinessRuleException("Weddings need a week's notice.");

        var perGuest = repo.findByWeddingTrue().stream()
            .map(i -> i.getUnitPrice().multiply(BigDecimal.valueOf(i.getPiecesPerGuest())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        var discount = guests >= 100 ? new BigDecimal("0.90") : BigDecimal.ONE; // the business rule
        return new QuoteDto(guests, perGuest.multiply(BigDecimal.valueOf(guests)).multiply(discount));
    }
}

// DATA ACCESS – repository/MenuItemRepository.java
interface MenuItemRepository extends JpaRepository<MenuItem, Long> {
    List<MenuItem> findByWeddingTrue();
}
catering.go
// PRESENTATION – internal/handler/catering.go
func (h CateringHandler) Quote(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Guests    int       `json:"guests"`
		EventDate time.Time `json:"eventDate"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	q, err := h.Service.Quote(r.Context(), req.Guests, req.EventDate)
	if err != nil {
		http.Error(w, err.Error(), http.StatusUnprocessableEntity)
		return
	}
	json.NewEncoder(w).Encode(q)
}

// BUSINESS – internal/service/catering.go
func (s CateringService) Quote(ctx context.Context, guests int, date time.Time) (Quote, error) {
	if date.Before(s.Now().AddDate(0, 0, 7)) {
		return Quote{}, errors.New("weddings need a week's notice")
	}
	menu, err := s.Repo.WeddingMenu(ctx) // *repository.CateringRepository: business imports data access
	if err != nil {
		return Quote{}, err
	}
	perGuest := 0.0
	for _, i := range menu {
		perGuest += float64(i.PiecesPerGuest) * i.UnitPrice
	}
	discount := 0.0
	if guests >= 100 {
		discount = 0.10 // the business rule lives here
	}
	return Quote{Guests: guests, Total: float64(guests) * perGuest * (1 - discount)}, nil
}
catering.py
# PRESENTATION – catering/api/quotes.py
@router.post("/api/catering/quotes")
def quote(req: QuoteRequest, service: CateringService = Depends(get_catering_service)) -> QuoteDto:
    try:
        return service.quote(req.guests, req.event_date)
    except BusinessRuleError as e:
        raise HTTPException(status_code=422, detail=str(e))


# BUSINESS – catering/services/catering.py
class CateringService:
    def __init__(self, repo: CateringRepository, today=date.today):
        self.repo, self.today = repo, today

    def quote(self, guests: int, event_date: date) -> QuoteDto:
        if event_date < self.today() + timedelta(days=7):
            raise BusinessRuleError("Weddings need a week's notice.")
        per_guest = sum(i.pieces_per_guest * i.unit_price for i in self.repo.wedding_menu())
        discount = Decimal("0.10") if guests >= 100 else Decimal("0")  # the business rule
        return QuoteDto(guests=guests, total=round(guests * per_guest * (1 - discount), 2))


# DATA ACCESS – catering/repositories/catering.py
class CateringRepository:
    def __init__(self, session: Session):
        self.session = session

    def wedding_menu(self) -> list[MenuItem]:
        return list(self.session.scalars(select(MenuItem).where(MenuItem.wedding.is_(True))))

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Where it breaks
  • Trade-offs
  • Evolution paths
  • In practice
  • Anti-patterns
  • Related topics
  • Test yourself

Create a free account · Sign in