📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

In a layered architecture, what are the dependency rules between layers, and what problems usually appear as the system grows? Explain strict vs relaxed layering, database-centric design and leaky layers.

Covers the dependency rules of layered architecture, strict versus relaxed layering, and the common failure modes: database-centric design, leaky layers, pass-through layers and the anaemic domain.

Junior Theory Intermediate anaemic-domain-model architecture dependency-rule ef-core layered-architecture leaky-abstraction

🎯 Key points

  • A layer may depend only on layers below it; never upwards, never cycles
  • Strict layering: only the layer directly below; relaxed: any lower layer — strict where rules must not be bypassed, relaxed for simple reads
  • Database-centric design: schema designed first, business layer shaped around tables, rules scattered across services and stored procedures
  • Leaky layer: lower-layer types (IQueryable, EF entities, SqlException) escape upwards — return DTOs and translated errors instead
  • Pass-through layers (sinkhole anti-pattern) add mapping and indirection but no logic
  • Enforce with project references, internal visibility and architecture tests (NetArchTest, ArchUnitNET) in CI
  • Remedies for complex domains: a rich domain model (DDD), dependency inversion (Clean/Hexagonal), or feature slices with CQRS-style reads

⏱ 30-second answer

The core rule: a layer may only depend on layers below it — presentation → business → data — never upwards and never in a cycle.

  • Strict layering allows calls only to the layer directly below; relaxed layering lets a layer skip down (for example a controller reading data directly for a simple query).
  • Database-centric design: because data access sits at the bottom, the schema is designed first and the business layer is shaped around tables, so rules leak into SQL and service classes.
  • Leaky layers: lower-layer types escape upwards — IQueryable, EF entities, SqlException in controllers.
  • Sinkhole layers: requests pass through layers that only map and forward.

The trade-off: layering is simple and familiar, but every feature cuts across all layers and the domain ends up depending on the database.

🗣 Full answer (senior)

How I would answer this in an interview

"The rule in a layered architecture is that dependencies only point down. Presentation may call the business layer, the business layer may call data access, and nothing below may know about anything above. In .NET I make the compiler enforce that with project references: Web references Business, Business references Data, and a reference the other way would create a cycle. Within that, there are two variants: strict layering, where you can only call the layer directly below, and relaxed layering, where a controller may skip straight to data access for a simple read. Relaxed is pragmatic, but each skip should be a conscious choice.

The problems appear as the system grows. The first is database-centric design: because data access is at the bottom, people design tables first, generate entities, and the business layer becomes a set of services that load rows, change fields and save them. Rules end up scattered across services and stored procedures. The second is leaky layers: the data layer returns IQueryable<Order> or EF entities, so the controller ends up composing queries and serialising entities with navigation properties — and now the UI depends on the schema. The third is the sinkhole: three layers where most requests just map a DTO to another DTO and pass it down, adding code without adding behaviour.

The mistake I see is blaming layering itself. Layering is fine for CRUD-heavy apps. What hurts is letting the database sit at the centre of a complex domain; that's exactly the dependency Clean and Hexagonal architectures invert."


The dependency rules

Rule Meaning How .NET enforces it
Downward only Higher layers depend on lower ones Project references; the compiler rejects circular references
No skipping (strict) Only the next layer down Not enforced by the compiler — needs architecture tests
Hide internals Each layer exposes a small public surface internal types, InternalsVisibleTo only for tests

Strict vs relaxed layering

Strict Relaxed
Calls allowed Next layer only Any lower layer
Benefit Changes stay local Less pass-through code
Cost Sinkhole layers, more mapping Easier to couple UI to data
Good for Systems with real rules in the middle Read-heavy, CRUD-heavy apps

Typical problems and their symptoms

Problem Symptom in code Consequence
Database-centric design Entities generated from tables; services named OrderTableService Rules scattered; schema changes ripple everywhere
Leaky layer IQueryable<T> or EF entities returned to controllers; DbUpdateException caught in controllers UI coupled to schema; N+1 queries from serialisation
Sinkhole OrderController → OrderService → OrderRepository each one line long Code with no behaviour, triple maintenance
Anaemic domain Entities with only public getters/setters, logic in *Service classes Invariants enforced in many places, or nowhere
Cross-cutting features One feature edits files in every layer Merge conflicts, slow change

Production example

A booking API returned EF entities from its data layer straight to controllers. A new navigation property caused System.Text.Json to serialise the whole graph, and one endpoint started issuing 120 lazy-loading queries per request — p95 rose from 80 ms to 1.9 s. Returning projected DTOs from the data layer, and switching lazy loading off, brought it back to 70 ms.

🔍 What the interviewer is checking

Checks that the candidate knows the dependency rules of layering and can recognise the problems it causes in real codebases.

Green flags

  • States the downward-only rule and how project references enforce it
  • Distinguishes strict and relaxed layering with a reason to pick each
  • Gives concrete leak examples such as IQueryable<T> or entities in controllers
  • Explains that the business layer depending on data access is the root issue

Red flags

  • Thinks controllers calling DbContext directly is always fine in a complex domain
  • Cannot name any downside of layered architecture
  • Confuses layering problems with "too many layers" only

📚 Learn in depth

1. Why dependencies point one way

If A depends on B, a change to B can break A, but not the other way round. Pointing all dependencies one way means the bottom layers are the most stable and the top layers the most volatile. Cycles destroy that: change anything in the cycle and everything in it may break.

Presentation  -->  Business  -->  Data  -->  SQL Server
  (volatile)                    (stable?)

The catch in the classic layout: data access is at the bottom, so the business layer depends on it. Your most important code (the rules) depends on your most technical code (EF Core, SQL).

2. Strict vs relaxed in practice

Strict:                      Relaxed:
Web -> Business -> Data      Web -> Business -> Data
                             Web -------------> Data   (allowed skip)

The compiler can't tell these apart — both are just project references. Only an architecture test (NetArchTest, ArchUnitNET) or a code review rule can stop Web from using Data in a strict design.

3. How a layer leaks

A layer leaks when its implementation details become part of its contract:

  • IQueryable<T>: the caller can add Where, Include and Skip, so the query is really built in the controller and the data layer's performance guarantees are gone.
  • EF entities: the shape of a table becomes the shape of the API; adding a column changes the JSON.
  • Provider exceptions: SqlException number 2627 (unique key violation) caught in a controller ties HTTP code to SQL Server.
  • Persistence concerns in the domain: [Column] attributes and virtual navigation properties for lazy loading.

4. Database-centric design

The typical path:

  1. Design the schema in SSMS.
  2. Scaffold entities (dotnet ef dbcontext scaffold).
  3. Write services that load entities, set properties and call SaveChanges.

The result: every rule ("an order can't be cancelled after dispatch") lives in whatever service happens to change that field. Two services can change it two different ways. This is the anaemic domain model Martin Fowler described.

5. Cross-cutting change

Layers are horizontal slices, but features are vertical. Adding "order notes" touches the controller, the DTO, the service, the repository, the entity and the migration. That is why Vertical Slice Architecture groups code by feature instead.

Try it yourself

  1. In a sample project, return IQueryable<Order> from a repository, add .Include(o => o.Lines) in the controller, and see the generated SQL in the EF Core logs.
  2. Turn on lazy loading proxies, return an entity with a navigation property from an endpoint and count queries with LogTo(Console.WriteLine).
  3. Pick one feature in your codebase and list how many projects you'd edit to add one field.
  4. Write a single architecture test asserting Web doesn't reference Data (strict layering).

💻 Code

A leaky data layer and the fixed version: the contract exposes results, not query machinery.

// Before: the data layer leaks EF Core upwards.
namespace Shop.Data;

public sealed class LeakyOrderRepository(ShopDbContext db)
{
    // The caller can compose anything onto this, including Include and ToList on huge tables.
    public IQueryable<Order> Query() => db.Orders;
}

// Controller in Shop.Web now depends on EF Core and the schema:
// var orders = repo.Query().Include(o => o.Lines).Where(o => o.Status == "Open").ToList();
// After: the data layer returns exactly what the use case needs.
namespace Shop.Data;

public sealed record OpenOrderDto(int Id, string Customer, decimal Total, int LineCount);

public interface IOrderQueries
{
    Task<IReadOnlyList<OpenOrderDto>> GetOpenOrdersAsync(int page, int pageSize, CancellationToken ct);
}

internal sealed class OrderQueries(ShopDbContext db) : IOrderQueries
{
    public async Task<IReadOnlyList<OpenOrderDto>> GetOpenOrdersAsync(int page, int pageSize, CancellationToken ct) =>
        await db.Orders
            .AsNoTracking()
            .Where(o => o.Status == OrderStatus.Open)
            .OrderBy(o => o.Id)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            // Projection: one SQL query, no entities or navigation properties leave this layer.
            .Select(o => new OpenOrderDto(o.Id, o.CustomerName, o.Total, o.Lines.Count))
            .ToListAsync(ct);
}
// Shop.Data/DependencyInjection.cs — the implementation stays internal; only the interface is public.
namespace Shop.Data;

using Microsoft.Extensions.DependencyInjection;

public static class DependencyInjection
{
    public static IServiceCollection AddShopData(this IServiceCollection services)
    {
        services.AddScoped<IOrderQueries, OrderQueries>();
        return services;
    }
}

⚠ Common mistakes

  • Mistake: Returning IQueryable<T> from the data layer. Why it is wrong: query construction moves into callers, so performance and correctness can't be reasoned about in one place. Instead: return materialised results or DTOs from purpose-built methods.
  • Mistake: Returning EF entities from API endpoints. Why it is wrong: the API contract follows the schema, over-posting becomes possible and serialising navigation properties triggers extra queries or cycles. Instead: project to DTOs.
  • Mistake: Catching SqlException or DbUpdateException in controllers. Why it is wrong: HTTP code now depends on the database provider. Instead: translate to a domain or application error in the lower layer.
  • Mistake: Adding a pass-through service for every repository method. Why it is wrong: it creates sinkhole layers with no behaviour. Instead: use relaxed layering for simple reads, or organise by feature.
  • Mistake: Designing tables first and putting rules in whatever service updates a column. Why it is wrong: the same rule ends up in several places, or nowhere. Instead: model the behaviour first and let persistence follow.
  • Mistake: Relying on reviewers to catch layer violations. Why it is wrong: skips creep in under deadline pressure. Instead: encode the rules as architecture tests that fail the build.

🏛 Senior insight: trade-offs

Layered architecture isn't wrong; it is a fit for simple, data-shaped domains. Its real flaw is that the business layer depends on data access, so the core of the system depends on its most volatile technology. When the domain has meaningful rules, I invert that dependency (Clean or Hexagonal) and model behaviour first with DDD tactics — entities that enforce their own invariants, aggregates as consistency boundaries — so persistence follows the model instead of shaping it. When it's mostly CRUD, I relax the layering or organise by feature, using CQRS-style read handlers that project straight to DTOs, to kill the sinkholes.

Whatever I choose, I make it enforced, not remembered: project references for direction, internal for implementation types, and a handful of architecture tests in CI ("Web must not reference Data", "no type outside Data uses DbContext"). That turns a layering decision into a fitness function that fails the build.

Option When it fits Cost When not to
Strict layering Real rules in the business layer Pass-through code, more mapping CRUD screens with no rules
Relaxed layering Read-heavy, simple apps Easier to couple UI to schema Complex rules that must not be bypassed
Inverted (Clean/Hexagonal) + rich domain Complex domain, long-lived system More projects and interfaces Small, short-lived apps
Vertical slices + CQRS reads Many independent features Less shared structure Rules shared across many features

A cheap health check: count how many projects a typical feature touches and how many layers contain no logic. Both numbers tell you whether the layering is paying for itself.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions repositories returning IQueryable or a generic IRepository<T>. Why: Checks whether they understand why a generic repository over EF Core is often an anti-pattern.
    How to answer

    A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.

    In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:

    • IQueryable<T> GetAll() leaks EF semantics to callers.
    • Save() per repository breaks the unit of work.
    • It invites repositories for child entities, which bypass the aggregate's rules.

    A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.

  2. When: Candidate mentions all logic sitting in service classes. Why: Checks whether they can separate application and domain services and recognise the anaemic domain model.
    How to answer

    These are three layers of responsibility:

    • An application service (Fowler's service layer) runs one use case. It loads aggregates through repositories, calls domain logic, commits the unit of work and publishes events. It handles transactions, authorisation and mapping, but holds no business rules.
    • A domain service holds stateless business logic that doesn't belong to one entity, often spanning aggregates (a funds transfer, a pricing policy). It's named in domain language and knows nothing about HTTP or EF Core.
    • Entities and value objects own their own invariants (order.Submit()), and they come first.

    When everything goes into a fat OrderService, entities become property bags: the anaemic domain model. Controllers should only translate HTTP. The trade-off is richer models and clear boundaries against more types and more thought about where each rule lives.

  3. When: Candidate says the business layer should not depend on data access. Why: Checks whether they can explain how Clean Architecture inverts that dependency.
    How to answer

    Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.

    • Domain (centre): entities, value objects, domain events and business rules — no EF Core, no ASP.NET Core.
    • Application: use cases (commands, queries, handlers) plus the interfaces they need, such as IOrderRepository or IEmailSender.
    • Infrastructure: implements those interfaces with EF Core, Azure Service Bus, Blob Storage.
    • Presentation: endpoints and the composition root that wires implementations to interfaces.

    The key move is dependency inversion: the database depends on the domain, not the other way round. The trade-off: testable, technology-independent rules in exchange for more projects, interfaces and mapping — overkill for simple CRUD.

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me