Layered Architecture (N-Tier Architecture) – A Detailed Explanation with Example

What is Layered Architecture?

Layered Architecture is a design pattern where an application is structured into multiple layers, each serving a specific role and handling a distinct responsibility. This separation of concerns enhances maintainability, scalability, and flexibility.

Key Layers

Example. E-Commerce System

Code Structure in .NET

// OrderController.cs (Presentation Layer)
public class OrderController : Controller
{
    private readonly OrderService _orderService;

    public OrderController(OrderService orderService)
    {
        _orderService = orderService;
    }

    [HttpPost]
    public IActionResult PlaceOrder(Order order)
    {
        _orderService.ProcessOrder(order);
        return Ok("Order placed successfully!");
    }
}

Business Logic Layer (Service Layer)

// OrderService.cs
public class OrderService
{
    private readonly OrderRepository _orderRepository;

    public OrderService(OrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public void ProcessOrder(Order order)
    {
        order.TotalAmount = order.Quantity * order.UnitPrice;
        _orderRepository.SaveOrder(order);
    }
}

Data Access Layer (Repository Layer)

// OrderRepository.cs
public class OrderRepository
{
    private readonly ApplicationDbContext _context;

    public OrderRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public void SaveOrder(Order order)
    {
        _context.Orders.Add(order);
        _context.SaveChanges();
    }
}

Advantages

Disadvantages

Comparison: Layered vs Microservices

Feature Layered Architecture Microservices Architecture
Structure Organized into layers Divided into small services
Scalability Moderate Highly scalable
Complexity Medium High
Deployment Entire system redeployed Independent deployments
Technology Single tech stack Multiple stacks possible

When to Use Layered Architecture?

When to Avoid Layered Architecture?

Conclusion

Layered Architecture is an effective design pattern for structured applications, offering benefits like maintainability and scalability. However, for distributed applications, Microservices architecture might be a better alternative.