Monolithic architectures remain the dominant starting point for most applications, particularly when teams are small or domain boundaries are not yet well understood. In a traditional monolith, all concerns — HTTP handling, business logic, and data access — live within a single deployable process. This article explores the structure and flow of a typical .NET Core monolithic application, delves into design patterns like modular monoliths and vertical slices, and contrasts monoliths with microservices using detailed diagrams and trade-off tables. We round out the discussion with practical observability guidance.
Overview of Monolithic Architecture
A monolithic application packs all functionality into a single executable or binary, which hosts the user interface (UI), the business logic layer, and the data access logic. The advantage is simplicity of deployment and operational overhead, but that can become a liability as the codebase grows.
First, let's visualize the high-level architecture of a traditional monolith:
flowchart TB
A[HTTP Request] --> B[Controller Layer]
B --> C[Service (Business Logic) Layer]
C --> D[Repository (Data Access) Layer]
D --> E[(Database)]
style E fill:#f9f,stroke:#333,stroke-width:2pxFigure 1: High-Level Data Flow in a Monolithic .NET Core Application
The entire application, including API controllers, application services, repositories, EF Core DbContexts, models, and middleware, is packaged as one deployable unit.
Project Structure in .NET Core Monolith
A common organization for an e-commerce .NET Core monolith looks like this:
ECommerceApp/
├── Controllers/ ← Presentation layer
│ ├── ProductsController.cs
│ └── OrdersController.cs
├── Services/ ← Business logic layer
│ ├── ProductService.cs
│ └── OrderService.cs
├── Repositories/ ← Data access layer
│ ├── ProductRepository.cs
│ └── OrderRepository.cs
├── Models/ ← Domain entities / DTOs
│ ├── Product.cs
│ └── Order.cs
├── Data/
│ └── AppDbContext.cs ← EF Core DbContext
├── Middleware/ ← Cross-cutting concerns
│ └── ExceptionMiddleware.cs
└── Program.cs ← Composition root / DI wiring
This layout follows a classic layered pattern:
- Controllers handle HTTP requests and responses.
- Services contain domain logic and enforce business rules.
- Repositories encapsulate data access with EF Core.
- Models hold domain entities and data transfer objects (DTOs).
- Middleware applies cross-cutting concerns such as exception handling.
- Program.cs wires dependencies and configures the web host.
Modular Monolith vs. Traditional Monolith
A modular monolith partitions code by bounded contexts or domains within the same process, enforcing boundary constraints strictly at compile time but without physical service separation.
| Aspect | Traditional Monolith | Modular Monolith |
|---|---|---|
| Boundary Enforcement | Often weak; modules can reference each other freely | Stronger; modules respect boundaries via interfaces |
| Deployment | Single deployable unit | Single deployable unit |
| Team Scaling | Best for small teams | Good for medium teams with clear domain boundaries |
| Complexity | Can become a “big ball of mud” | Better maintainability using explicit boundaries |
| Infrastructure Overhead | Minimal | Minimal |
Request Flow: Placing an Order Walkthrough
Let's dig into the typical flow of a "Place an Order" request in a .NET Core monolith.
sequenceDiagram
participant Client
participant Controller as OrdersController
participant Service as OrderService
participant RepoP as ProductRepository
participant RepoO as OrderRepository
participant Db as AppDbContext
Client->>Controller: POST /api/orders (PlaceOrderRequest)
Controller->>Service: PlaceOrderAsync(request)
Service->>RepoP: GetByIdAsync(productId)
RepoP-->>Service: Product or null
alt Product exists and stock sufficient
Service->>Service: Create Order, update product stock
Service->>RepoO: AddAsync(order)
Service->>Db: SaveChangesAsync()
Service-->>Controller: orderId
Controller-->>Client: 201 Created (orderId)
else Out of stock or product missing
Service-->>Controller: throws Exception
Controller-->>Client: 400/404 Error Response
endFigure 2: Request-Response Sequence Diagram for "Place Order"
1. Controller Layer
Acts as the entry point for the HTTP request. It should be kept thin to delegate work to the service layer.
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
public OrdersController(IOrderService orderService)
=> _orderService = orderService;
[HttpPost]
public async Task<IActionResult> PlaceOrder([FromBody] PlaceOrderRequest request)
{
var orderId = await _orderService.PlaceOrderAsync(request);
return CreatedAtAction(nameof(GetOrder), new { id = orderId }, null);
}
}
Notice how the controller only parses input and forwards to the service. It does not contain any business logic.
2. Service Layer
Handles core domain logic: retrieving products, checking stock, calculating totals, and enforcing business rules.
public class OrderService : IOrderService
{
private readonly IOrderRepository _orders;
private readonly IProductRepository _products;
private readonly AppDbContext _db;
public OrderService(IOrderRepository orders, IProductRepository products, AppDbContext db)
{
_orders = orders;
_products = products;
_db = db;
}
public async Task<Guid> PlaceOrderAsync(PlaceOrderRequest request)
{
var product = await _products.GetByIdAsync(request.ProductId)
?? throw new NotFoundException("Product not found");
if (product.Stock < request.Quantity)
throw new BusinessException("Insufficient stock");
var order = new Order
{
Id = Guid.NewGuid(),
ProductId = product.Id,
Quantity = request.Quantity,
Total = product.Price * request.Quantity,
CreatedAt = DateTime.UtcNow
};
product.Stock -= request.Quantity;
await _orders.AddAsync(order);
await _db.SaveChangesAsync(); // single atomic transaction
return order.Id;
}
}
The service layer coordinates repositories and manages transactional consistency via EF Core’s
SaveChangesAsync.
3. Repository Layer
Abstraction over EF Core data access, exposing domain-friendly APIs.
public class ProductRepository : IProductRepository
{
private readonly AppDbContext _db;
public ProductRepository(AppDbContext db) => _db = db;
public Task<Product?> GetByIdAsync(Guid id)
=> _db.Products.FirstOrDefaultAsync(p => p.Id == id);
}
The repository pattern enables unit testing and keeps the service layer isolated from ORM concerns.
4. Composition Root: Program.cs
Dependency injection wiring configures service lifetimes and adds middleware.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(opts =>
opts.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseMiddleware<ExceptionMiddleware>();
app.MapControllers();
app.Run();
The DI container manages lifetimes, ensuring one DbContext per request and enabling testability via interface mock substitution.
Architectural Trade-offs: Monolith vs. Microservices
Choosing between a monolith and microservices depends heavily on your team and domain context.
| Aspect | Monolithic Architecture | Microservices Architecture |
|---|---|---|
| Deployment | Single deployable unit | Many independently deployable services |
| Operations | Simple (one process, one db, one deploy pipeline) | Complex (service discovery, distributed tracing) |
| Team Coordination | Easier with small teams (1–5 people) | Better for larger teams, aligned around services |
| Codebase Complexity | Can grow unwieldy; risks "big ball of mud" | Potentially cleaner boundaries, but distributed complexity |
| Data Management | Single relational database | Polyglot persistence, eventual consistency issues |
| Technology Diversity | Limited | Services can use different tech stacks |
| Latency | Lower, in-process calls | Higher, network calls |
| Testing | Easier local integration testing | Requires mocking external services |
| Scalability | Vertical scaling | Horizontal scaling at service level |
| Fault Isolation | Poor; bug affects whole app | Better fault isolation |
Vertical Slice Architecture: An Alternative
Instead of organizing by horizontal layers, vertical slice architecture groups code by feature:
ECommerceApp/
├── Orders/
│ ├── PlaceOrderHandler.cs
│ ├── PlaceOrderRequest.cs
│ ├── PlaceOrderValidator.cs
│ └── Order.cs
├── Products/
│ ├── GetProductHandler.cs
│ ├── Product.cs
│ └── ProductRepository.cs
└── Shared/
└── ...
This approach can be applied to monoliths and microservices alike. Benefits include:
- Better feature isolation and encapsulation
- Reduced need for large service teams to coordinate common layers
- Easier to reason about changes scoped to one vertical slice
- Facilitates gradual extraction of services later if needed
Observability for Monolithic .NET Core Applications
Observability is crucial to ensuring reliability and understanding runtime behavior. Focus on structured logging, metrics, distributed tracing, and SLIs/SLOs.
What to Log
Log important request lifecycle events and errors with structured data:
{
"timestamp": "2024-06-10T14:23:55Z",
"level": "Information",
"message": "Order placed successfully",
"orderId": "b9f3b7a1-7d5a-4e8f-865f-97f216585fee",
"productId": "4f6a2b7d-3479-4c24-9f86-209a718ac123",
"quantity": 3,
"userId": "user123",
"latencyMs": 42
}
Log exceptions with stack traces and error codes.
Key Metrics (RED for Services)
| Metric | Description | Tool Example |
|---|---|---|
| R Request rate | Number of incoming HTTP requests | Prometheus, Application Insights |
| E Errors | Count of failed or error responses | Prometheus, ELK stack |
| D Duration | Latency of requests (P95, P99) | Prometheus, Jaeger |
Key Metrics (USE for Resources)
| Resource | Metric | Purpose |
|---|---|---|
| CPU | Utilization, Saturation | Detect bottlenecks and spikes |
| Memory | Utilization, Errors | Detect leaks or OOM |
| Disk I/O | Throughput, Latency | Monitor DB or file system performance |
| Network | Throughput, Errors | Monitor connectivity issues |
Distributed Tracing with OpenTelemetry
Implementing distributed tracing inside a monolith helps identify slow code paths and bottlenecks.
// Program.cs snippet for OpenTelemetry
builder.Services.AddOpenTelemetryTracing(tracerProviderBuilder =>
{
tracerProviderBuilder
.AddAspNetCoreInstrumentation()
.AddEntityFrameworkCoreInstrumentation()
.AddConsoleExporter();
});
This captures traces for HTTP requests and EF Core database calls automatically.
SLIs / SLOs
| SLI | SLO (Example) |
|---|---|
| Request Success Rate | ≥ 99.95% successful requests |
| Request Latency P95 | < 300 ms |
| Error Rate | < 0.05% |
| Database Transaction Success | 100% |
Alerts Worth Paging
- Request error rate spike above SLO threshold for 5+ minutes
- P95 latency degradation > 2x baseline
- Unhandled exception frequency surge
- EF Core timeouts or transaction failures
- Database connectivity outages or saturation
Summary and Recommendations
The traditional .NET Core monolith remains a robust, simple, and cost-effective architecture for small teams and early-stage products, or when domain boundaries are unclear. Key practices to maintain its health include:
- Enforce separation of concerns through layers or modules.
- Keep controllers thin and delegate domain logic to services.
- Abstract data access via repository pattern.
- Use dependency injection and test interfaces.
- Follow modular monolith or vertical slice patterns if domain complexity grows.
- Build comprehensive observability early, including structured logs and telemetry.
- Think about eventual service extraction only after boundaries stabilize.
Monoliths are not inherently an anti-pattern; careful modularization within the monolith can deliver maintainability and flexibility similar to microservices without the distributed complexity and overhead.
Minimal Runnable Example
// Minimal setup to place an order in a monolith
var builder = WebApplication.CreateBuilder();
builder.Services.AddDbContext<AppDbContext>(opt => opt.UseInMemoryDatabase("ECom"));
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
This minimal example shows how dependency injection and EF Core come together in just a few lines with an in-memory database.
Realistic Runnable Example: PlaceOrder Endpoint with Logging and Validation
// Order Models
public record PlaceOrderRequest(Guid ProductId, int Quantity);
// Controller
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _service;
private readonly ILogger<OrdersController> _logger;
public OrdersController(IOrderService service, ILogger<OrdersController> logger)
{
_service = service;
_logger = logger;
}
[HttpPost]
public async Task<IActionResult> PlaceOrder([FromBody] PlaceOrderRequest req)
{
_logger.LogInformation("Received order for product {ProductId} with quantity {Quantity}", req.ProductId, req.Quantity);
if (req.Quantity <= 0)
return BadRequest("Quantity must be > 0");
try
{
var orderId = await _service.PlaceOrderAsync(req);
_logger.LogInformation("Order {OrderId} placed successfully", orderId);
return CreatedAtAction(nameof(GetOrder), new { id = orderId }, null);
}
catch (NotFoundException)
{
_logger.LogWarning("Product {ProductId} not found", req.ProductId);
return NotFound();
}
catch (BusinessException ex)
{
_logger.LogWarning("Business error: {Message}", ex.Message);
return BadRequest(ex.Message);
}
}
[HttpGet("{id}")]
public async Task<IActionResult> GetOrder(Guid id) =>
// Dummy placeholder
Ok(new { id, status = "submitted" });
}
This example adds logging, validation error handling, and structured logs for traceability, giving a more production-ready request lifecycle.
By applying these foundational monolithic patterns and observability techniques, .NET Core teams can build maintainable, reliable applications with room to grow into modular layered apps or microservices later. The monolith remains a pragmatic and powerful architecture well into modern software engineering practice.