Skip to content

All Major Architectures in .NET Core

1. Monolithic Architecture Extracted description: A single codebase and single deployable unit where all components are tightly coupled. Structure: UI / Web API → Business Logic + Data Access + Shared Components → Databa...

Ekanatha Reddy Urivakili15 min2,029 words

1. Monolithic Architecture

Extracted description:
A single codebase and single deployable unit where all components are tightly coupled.

Structure:
UI / Web API → Business Logic + Data Access + Shared Components → Database

Pros:

  • Easy to develop and deploy
  • Simple to test
  • Good performance because there are no network calls between internal components

Cons:

  • Hard to scale
  • Tightly coupled
  • Technology lock-in

Best for:

  • Small applications
  • MVPs
  • Prototypes
  • Applications where the domain is simple

Detailed explanation

Monolithic architecture is the simplest and most traditional way to build a .NET Core application. The entire application is packaged and deployed as one unit. Your controllers, services, business logic, repositories, authentication, background jobs, and data access usually live in the same application.

A common .NET Core monolith may look like this:

ASP.NET Core MVC / Web API
 ├── Controllers
 ├── Services
 ├── Repositories
 ├── Entity Framework Core
 ├── Domain Models
 └── SQL Server / PostgreSQL

This is a good starting point for most new applications because it is easy to build, debug, test, and deploy. You do not need service discovery, API gateways, message brokers, distributed tracing, or complex DevOps pipelines.

The problem appears when the application grows. Since everything is inside one deployable unit, a small change in one feature may require redeploying the whole application. Scaling is also less flexible. For example, if only the reporting module needs more resources, you still have to scale the entire application.

Good example:
A small expense-splitting application, blog platform, admin dashboard, internal CRM, or MVP SaaS product.

Avoid when:
You already know the system will have many teams, high traffic, independent modules, or very different scalability needs.


2. N-Tier Architecture

Extracted description:
Application is divided into layers such as Presentation, Business Logic, and Data Access.

Structure:
Presentation UI → Business Logic → Data Access → Database

Pros:

  • Separation of concerns
  • More organized
  • Maintainable structure

Cons:

  • Still tightly coupled
  • Changes in one layer can impact others

Best for:

  • Enterprise applications with clear separation of concerns

Detailed explanation

N-Tier architecture separates the application into technical layers. In .NET Core, this commonly means separating the project into different class libraries.

A typical structure:

MyApp.Api
MyApp.Business
MyApp.DataAccess
MyApp.Models
MyApp.Database

The presentation layer handles incoming HTTP requests. The business logic layer handles rules and workflows. The data access layer communicates with the database using Entity Framework Core, Dapper, or raw SQL.

This architecture is better than a completely unstructured monolith because responsibilities are clearer. Developers know where controllers, services, repositories, and models should live.

However, N-Tier architecture can still become tightly coupled. For example, the business layer may depend heavily on the data access layer. Over time, database models may leak into API responses, and changes in one layer may force changes in other layers.

Good example:
A corporate HR system, finance system, order management system, or internal enterprise web application.

Avoid when:
The business domain is complex and you need strong domain boundaries. In that case, Clean Architecture or Vertical Slice Architecture may be better.


3. Clean Architecture

Extracted description:
A dependency rule-based architecture that keeps business rules independent of frameworks and UI.

Layers:
Entities → Domain → Application → UI / External
With interfaces, use cases, adapters, frameworks, and drivers.

Pros:

  • Highly maintainable
  • Testable
  • Independent of UI, database, and frameworks

Cons:

  • More initial setup
  • Steeper learning curve

Best for:

  • Complex, long-term projects that need to be scalable and testable

Detailed explanation

Clean Architecture focuses on protecting the core business logic from external concerns such as databases, APIs, UI frameworks, third-party services, and infrastructure.

The most important rule is:

Dependencies point inward.

That means the domain layer should not depend on Entity Framework, ASP.NET Core, SQL Server, Redis, RabbitMQ, or any external framework. Instead, the core application defines interfaces, and the infrastructure layer implements them.

A common .NET Core Clean Architecture structure:

MyApp.Domain
 ├── Entities
 ├── ValueObjects
 ├── DomainEvents
 └── BusinessRules

MyApp.Application
 ├── UseCases
 ├── Commands
 ├── Queries
 ├── Interfaces
 └── DTOs

MyApp.Infrastructure
 ├── Database
 ├── Repositories
 ├── External APIs
 ├── Email
 └── File Storage

MyApp.Api
 ├── Controllers
 ├── Middleware
 └── Dependency Injection

For example, the Application layer may define:

public interface IExpenseRepository
{
    Task<Expense> GetByIdAsync(Guid id);
    Task SaveAsync(Expense expense);
}

The Infrastructure layer then implements it using Entity Framework Core.

Clean Architecture makes testing easier because business logic can be tested without a database or web server. It also makes the application easier to change. For example, you can replace SQL Server with PostgreSQL, or replace an MVC UI with a React frontend, without rewriting the core business logic.

Good example:
A banking application, insurance platform, SaaS product, accounting system, or complex business workflow application.

Avoid when:
You are building a very small prototype or simple CRUD app. The setup may feel heavy at the beginning.


4. Vertical Slice Architecture

Extracted description:
Organize the application by features or slices rather than technical layers. Each feature is end-to-end.

Structure per slice:
Feature / Slice 1 → API / UI → Business Logic → Data Access
Feature / Slice 2 → API / UI → Business Logic → Data Access
Feature / Slice N → API / UI → Business Logic → Data Access

Pros:

  • High cohesion
  • Low coupling
  • Faster development
  • Easy to scale by feature

Cons:

  • Requires good team discipline

Best for:

  • Modern API applications
  • Agile teams
  • Feature-focused development

Detailed explanation

Vertical Slice Architecture organizes code by feature instead of by technical layer. Instead of having one big Controllers folder, one Services folder, and one Repositories folder, each feature owns its own request, validation, business logic, and data access.

Example structure:

Features
 ├── Expenses
 │   ├── CreateExpense
 │   │   ├── Command.cs
 │   │   ├── Handler.cs
 │   │   ├── Validator.cs
 │   │   └── Endpoint.cs
 │   ├── GetExpenseById
 │   └── DeleteExpense
 │
 ├── Groups
 │   ├── CreateGroup
 │   ├── AddMember
 │   └── GetGroupBalance
 │
 └── Settlements
     ├── CreateSettlement
     └── ConfirmSettlement

Each slice is independent and contains everything required for that feature. This reduces the risk of one feature affecting another.

Vertical Slice Architecture works very well with CQRS and MediatR in .NET Core. For example, each command or query can have its own handler.

Instead of thinking:

Controller → Service → Repository

You think:

CreateExpense feature
GetExpense feature
SplitExpense feature
SettleBalance feature

This is very useful for agile development because teams usually work on features, not layers.

Good example:
A modern SaaS API, expense-splitting app, social media app, article platform, booking system, or marketplace.

Avoid when:
The team is not disciplined. Without rules, duplicate logic can appear across multiple slices.


5. Microservices Architecture

Extracted description:
Application is broken down into small, independent services that communicate over a network.

Structure:
Client → API Gateway → Service 1 → DB 1
Client → API Gateway → Service 2 → DB 2
Client → API Gateway → Service N → DB N

Pros:

  • Independent deployment
  • Highly scalable
  • Technology flexibility
  • Fault isolation

Cons:

  • Complex to design, deploy, and manage
  • Network latency

Best for:

  • Large-scale systems with multiple teams and high scalability requirements

Detailed explanation

Microservices architecture splits a large application into multiple independent services. Each service owns a specific business capability and usually has its own database.

Example for an e-commerce system:

User Service
Product Service
Order Service
Payment Service
Inventory Service
Notification Service

Each service can be developed, deployed, scaled, and maintained independently.

In .NET Core, a microservice may be a separate ASP.NET Core Web API. Services may communicate using HTTP, gRPC, RabbitMQ, Kafka, Azure Service Bus, or AWS SQS/SNS.

A typical structure:

Frontend / Mobile App
        ↓
API Gateway
        ↓
 ┌───────────────┬───────────────┬───────────────┐
 User Service    Order Service    Payment Service
 User DB         Order DB         Payment DB

Microservices are powerful but expensive in terms of complexity. You need proper DevOps, CI/CD, observability, logging, monitoring, distributed tracing, service discovery, retry policies, circuit breakers, security, and data consistency strategies.

One common mistake is starting with microservices too early. If the domain is not well understood, you may split services incorrectly and create unnecessary complexity.

Good example:
Netflix-style streaming systems, large e-commerce platforms, banking platforms, logistics systems, ride-sharing platforms, and enterprise SaaS products with many teams.

Avoid when:
You are building an MVP, small product, or early-stage startup app. A modular monolith or clean architecture is usually better at the beginning.


6. CQRS Architecture

Extracted description:
Separate read/query and write/command operations for better performance and scalability.

Structure:
Command side/write side:
Command → Command Handler → Write DB

Query side/read side:
Query → Query Handler → Read DB / Cache

Pros:

  • Optimized performance
  • Scalable read and write
  • Better separation

Cons:

  • More complex
  • Data consistency management

Best for:

  • Systems with high read/write load
  • Reporting
  • Analytics
  • Complex domains

Detailed explanation

CQRS stands for Command Query Responsibility Segregation.

It separates operations that change data from operations that read data.

Command = Write operation
Query = Read operation

Examples of commands:

CreateExpense
UpdateArticle
ApprovePayment
CancelOrder

Examples of queries:

GetExpenseById
GetUserBalance
GetMonthlyReport
SearchArticles

In a simple CQRS setup, commands and queries may still use the same database. In a more advanced setup, writes go to a normalized transactional database, while reads come from a separate optimized read database, cache, or search index.

Example:

Write side:
API → CreateOrderCommand → Handler → SQL Database

Read side:
API → GetOrderSummaryQuery → Handler → Redis / Elasticsearch / Read DB

CQRS is very useful when read and write requirements are different. For example, writing an order requires validation and transactional consistency, but reading dashboards may need fast aggregated data.

CQRS is often combined with Event Sourcing, MediatR, Domain Events, RabbitMQ, Kafka, Redis, or Elasticsearch.

Good example:
Banking transactions, reporting dashboards, analytics platforms, order systems, article feeds, notification systems, or high-traffic APIs.

Avoid when:
The application is simple CRUD. CQRS can add unnecessary complexity if reads and writes are straightforward.


7. Event-Driven Architecture

Extracted description:
Components communicate by producing and consuming events via an event broker.

Structure:
Event Producer → Event Broker / Message Bus → Event Consumer

Pros:

  • Loose coupling
  • Scalable
  • Real-time processing
  • Resilient systems

Cons:

  • Eventual consistency
  • Harder to debug

Best for:

  • Real-time systems
  • Integration between services
  • IoT
  • Stream processing

Detailed explanation

Event-Driven Architecture allows different parts of a system to communicate through events.

An event is something that has already happened.

Examples:

UserRegistered
ExpenseCreated
PaymentCompleted
OrderShipped
ArticlePublished
CommentAdded

Instead of one service directly calling another service, it publishes an event to a message broker. Other services listen to that event and react.

Example:

Expense Service publishes: ExpenseCreated

Consumers:
 ├── Notification Service sends email
 ├── Analytics Service updates dashboard
 ├── Audit Service stores history
 └── Balance Service recalculates user balance

This reduces coupling because the Expense Service does not need to know who is listening. It only publishes the event.

In .NET Core, this can be implemented using:

RabbitMQ
Kafka
Azure Service Bus
AWS SNS/SQS
MassTransit
NServiceBus
CAP

Event-driven systems are excellent for scalability and resilience. If one consumer is temporarily down, the event can remain in the queue and be processed later.

However, debugging is harder because the flow is asynchronous. Data may also be eventually consistent. For example, a payment may complete now, but the reporting dashboard may update a few seconds later.

Good example:
Notification systems, payment workflows, real-time analytics, IoT systems, order processing, audit logging, and integration between multiple services.

Avoid when:
You need simple synchronous CRUD behavior and immediate consistency everywhere.


Quick Comparison

ArchitectureMain IdeaComplexityBest Use Case
MonolithicEverything in one deployable appLowMVPs, small apps
N-TierSeparate by technical layersLow to MediumEnterprise CRUD apps
Clean ArchitectureKeep business logic independentMediumLong-term complex systems
Vertical SliceOrganize by featureMediumModern APIs and agile teams
MicroservicesSplit into independent servicesHighLarge systems, many teams
CQRSSeparate reads and writesMedium to HighHigh-performance read/write systems
Event-DrivenCommunicate using eventsHighReal-time and distributed systems

Practical Recommendation for .NET Core Projects

For most real-world .NET Core applications, the best starting point is usually:

Clean Architecture + Vertical Slice + Modular Monolith

This gives you:

  • Strong maintainability
  • Clear feature boundaries
  • Easier testing
  • Lower complexity than microservices
  • A future path to microservices if needed

For example, for a SaaS web app like an article platform, expense-sharing app, or admin-driven content system, I would usually start with:

ASP.NET Core Web API
React / Next.js frontend
PostgreSQL or SQL Server
Entity Framework Core
Clean Architecture
Vertical Slice feature folders
Redis for caching if needed
Background jobs using Hangfire or Quartz
Docker for local and deployment setup

Then, only move to microservices when there is a real business or scaling reason.

category: tech-stacks

Architecture High-Level Diagram

flowchart LR
    UI["UI / Web API"] --> BL["Business Logic"]
    BL --> DAL["Data Access Layer"]
    DAL --> DB["Database"]
    UI -.-> Ext["External APIs / Services"]

    subgraph Monolith
      UI
      BL
      DAL
      DB
    end

    subgraph N_Tier
      UI --> BL --> DAL --> DB
    end

    subgraph Clean_Architecture
      UI --> ApplicationLayer --> DomainLayer --> DB[Database / External services]
      ApplicationLayer -- Interfaces --> InfrastructureLayer
      InfrastructureLayer --> DB
    end

    subgraph Vertical_Slice
      subgraph Feature1
        F1_API --> F1_BizLogic --> F1_DataAccess --> DB1
      end
      subgraph Feature2
        F2_API --> F2_BizLogic --> F2_DataAccess --> DB2
      end
    end

    subgraph Microservices
      API_Gateway --> Service1 --> DB_1
      API_Gateway --> Service2 --> DB_2
      API_Gateway --> ServiceN --> DB_N
    end

    subgraph CQRS
      CommandAPI --> CommandHandler --> WriteDB
      QueryAPI --> QueryHandler --> ReadDB
    end

    subgraph EventDriven
      Producer --> Broker --> Consumer1
      Broker --> Consumer2
    end

High-level flow of commonly used .NET Core architectures showing component interactions

Sequence Diagram: Typical Clean Architecture Request Flow

sequenceDiagram
    participant Client
    participant ApiController
    participant Application
    participant Domain
    participant Infrastructure
    participant Database

    Client ->> ApiController: HTTP Request (e.g., CreateExpense)
    ApiController ->> Application: Send Command (CreateExpenseCommand)
    Application ->> Domain: Validate Business Rules
    Domain -->> Application: Validation result
    Application ->> Infrastructure: Call Repository.SaveAsync()
    Infrastructure ->> Database: Insert Expense
    Database -->> Infrastructure: Success
    Infrastructure -->> Application: Save result
    Application -->> ApiController: Command completion
    ApiController -->> Client: HTTP Response (e.g., 201 Created)

Request flow from API controller down to the database in Clean Architecture

Code Example 1: Minimal Vertical Slice Feature using MediatR in .NET Core

// CreateExpense/Command.cs
public record Command(string Description, decimal Amount) : IRequest<Guid>;

// CreateExpense/Handler.cs
public class Handler : IRequestHandler<Command, Guid>
{
    private readonly IExpenseRepository _repository;
    public Handler(IExpenseRepository repository) => _repository = repository;

    public async Task<Guid> Handle(Command request, CancellationToken cancellationToken)
    {
        var expense = new Expense(Guid.NewGuid(), request.Description, request.Amount);
        await _repository.SaveAsync(expense);
        return expense.Id;
    }
}

// Usage in API controller (ASP.NET Core minimal API)
app.MapPost("/expenses", async (Command command, IMediator mediator) =>
{
    var id = await mediator.Send(command);
    return Results.Created($"/expenses/{id}", new { id });
});

Notice how the entire feature lives within its slice: the command, its handler, and API endpoint are all colocated.

Code Example 2: Clean Architecture - Repository Interface and Implementation

// Domain Layer - IExpenseRepository.cs
public interface IExpenseRepository
{
    Task<Expense> GetByIdAsync(Guid id);
    Task SaveAsync(Expense expense);
}

// Infrastructure Layer - ExpenseRepository.cs
public class ExpenseRepository : IExpenseRepository
{
    private readonly AppDbContext _context;
    public ExpenseRepository(AppDbContext context) => _context = context;

    public async Task<Expense> GetByIdAsync(Guid id) =>
        await _context.Expenses.FindAsync(id);

    public async Task SaveAsync(Expense expense)
    {
        _context.Expenses.Add(expense);
        await _context.SaveChangesAsync();
    }
}

The domain only depends on the interface, which is implemented in infrastructure and can change independently.

Observability for .NET Core Architectures

What to Log

  • Incoming requests: method, path, headers, user context
  • Business events: domain events, command execution results
  • Data access calls: queries executed, latency, errors
  • External API calls and messaging events
  • Exceptions with full stack traces
  • Background job execution and results

Example structured log entry (JSON):

{
  "timestamp": "2024-06-01T12:34:56Z",
  "level": "Information",
  "logger": "MyApp.Api.Features.Expenses.CreateExpense.Handler",
  "message": "Expense created successfully",
  "expenseId": "f3a4c1d2-9c66-4f1e-ba39-7559d7201234",
  "userId": "user-123",
  "durationMs": 150,
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}

Key Metrics

Metric TypeKey MetricsDescription
RED (Requests)Request rate, Success rate, Error rateMeasure request throughput and failures
Request latency (P50, P95, P99)Latency percentiles
USE (Resources)CPU, Memory, Thread pool usageSystem resource usage
DB connection pool usageData access health

Distributed Tracing with OpenTelemetry (.NET Core Sample)

using OpenTelemetry.Trace;
using OpenTelemetry.Resources;

builder.Services.AddOpenTelemetryTracing(tracerProviderBuilder =>
{
    tracerProviderBuilder
        .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyApp.Api"))
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddEntityFrameworkCoreInstrumentation()
        .AddJaegerExporter(options =>
        {
            options.AgentHost = "localhost"; // configure as needed
            options.AgentPort = 6831;
        });
});

Add tracing to correlate requests across layers and services, critical for Microservices and Event-Driven architectures.

SLI/SLO Table

SLITarget / SLONotes
Request success rate99.9% successful responsesPer minute window
Request latency (P95)< 300 msFor API calls
Error rate< 0.1%Count of 5xx or handled exceptions
Database query latency< 100 msAverage query execution
Event processing latency< 1 s for 95% of eventsFor event-driven architectures

Alerts Worth Paging

  • API error rate above threshold (e.g. 5xx spike)
  • Request latency beyond SLA limits for sustained period
  • Database connection pool exhaustion
  • Event broker queue depth high or consumer lag
  • Service crash or restart frequency
  • Background job failures exceeding threshold

This material adds actionable diagrams, realistic .NET Core code, and observability guidance for all major .NET Core architectures discussed in the article.