Scalable .NET 8 API: Clean Architecture, CQRS, JWT, PostgreSQL and Redis - Complete Guide

Discover how to build a Web API in .NET 8 following Clean Architecture and CQRS with MediatR, JWT, PostgreSQL, and Redis, using Docker, testing, and CI/CD.

domingo, 17 de agosto de 2025 • 5 min read • Q2BSTUDIO Team

Artificial-Intelligence-

All .NET developers have gone through the same experience: starting a project with good intentions, applying SOLID principles and writing clean code, and after a few months a monolithic controller appears with dozens of methods, scattered business logic, and a test suite that breaks with any change in the database.

The problem is not your programming skills but the architecture. Tutorials usually show simple APIs that work for demos but fall apart in production. In this translated and adapted article, you will learn how to build a production-ready Web API in .NET 8 following Clean Architecture with CQRS, JWT authentication, PostgreSQL persistence, and distributed caching with Redis.

This guide is not a simple example of basic tasks; we are going to model an application for a bakery that can meet real requirements, scale to thousands of users, and remain maintainable as the team grows.

Proposed architecture: layers and responsibilities: domain, application, infrastructure, and presentation. The domain layer contains entities and pure business rules without external dependencies. The application layer orchestrates use cases through CQRS and MediatR. The infrastructure layer handles the database, caching, external services, and authentication. The presentation layer manages controllers, middleware, and DTOs.

Key technologies: .NET 8 for performance and modern features; PostgreSQL as a robust relational engine; Redis for in-memory caching and distributed sessions; Entity Framework Core as ORM; MediatR to implement the mediator pattern and support CQRS; FluentValidation for expressive validations; JWT authentication for stateless APIs; Docker for consistency in development and deployment.

Suggested project structure: src with projects BakingApp.Domain, BakingApp.Application, BakingApp.Infrastructure, BakingApp.API, and a tests folder with unit and integration tests. The dependency flow is strictly maintained toward the domain layer to protect business logic from infrastructure changes.

Domain layer: entities and business exceptions go here. Keeping domain objects simple and expressive facilitates testing and reuse. Domain exceptions communicate rule violations in business language, avoiding dependence on database errors.

Application layer: we apply CQRS, separating commands for operations that mutate state and queries for reading. Each command or query has a unique handler, which improves clarity, scalability, and testability. Using records for commands and responses provides immutability and concise syntax.

Validation: FluentValidation allows complex rules and clear messages. Integrated as a pipeline behavior in MediatR, validation runs before handlers, ensuring that only correct inputs reach business logic.

Patterns in handlers: dependency injection through interfaces for data context, password hashing, token generator, and cache service. Error handling through domain exceptions, immediate caching after critical operations, data normalization, and asynchronous operations for scalability.

Infrastructure: DbContext with EF Core configured for PostgreSQL using explicit constraints, maximum lengths, unique indexes, database defaults, and automatic timestamp updates. In the infrastructure layer, services such as JwtTokenGenerator, CacheService, and PasswordHasher are implemented following good security practices.

JWT: token generation with standard claims: user id, email, role, jti, and iat. Signed with HMAC SHA256 and a sufficiently long secret, with expiration configurable by environment to support key rotation and security policies.

Redis distributed caching: generic implementation that uses IDistributedCache, storing objects serialized in JSON with camelCase, handling configurable expirations, and fault tolerance through logs so that cache errors do not break the application.

Password hashing: use the ASP.NET Core Identity hasher, which offers PBKDF2 with SHA256, random salt, and support for rehashing when security policies change.

API layer: thin controllers that delegate to MediatR, validate through the pipeline, and return consistent responses. Global exception middleware provides uniform responses for validation errors, domain exceptions, authorization failures, and internal errors without leaking sensitive details.

Pipeline configuration: register MediatR, validators, pipeline behaviors, and infrastructure services in program.cs; enable Swagger in development, CORS, and exception middleware. Keep configuration separated by environments and use secret providers in production.

Development with Docker Compose: defining services for PostgreSQL and Redis with persistent volumes, private network, and secure passwords makes it easy to spin up a reproducible environment for the whole team.

Configuration and secrets management: keep connection strings and settings in per-environment files or, better yet, in cloud secret services. For deployment, use cloud services from AWS and Azure, taking advantage of managed database instances, managed caches, and identity solutions.

Testing: write unit tests for handlers and integration tests for the infrastructure layer using in-memory databases or containers. EF Core InMemory does not replace tests with real PostgreSQL. Automate migrations and tests in CI/CD.

Good security practices: validate and sanitize inputs, always use HTTPS, separate roles and permissions in claims, apply throttling and protections against replay attacks, log security events, and monitor in real time.

Benefits of this approach: separation of responsibilities, easy maintenance, scalability, the possibility of scaling reads and writes independently, greater test coverage, and reduced risk when introducing changes.

About Q2BSTUDIO: we are a software development company specializing in custom applications and custom software, experts in artificial intelligence, cybersecurity, cloud services AWS and Azure, business intelligence services, and implementation of AI solutions for companies. We help organizations design and build scalable, secure, and maintainable systems, including AI agents, Power BI integration, and custom artificial intelligence projects to improve processes and obtain real value from data.

Featured services from Q2BSTUDIO: custom application development, custom software consulting, implementation of artificial intelligence projects, AI agents, cybersecurity solutions, integration and migration to AWS and Azure cloud services, and business intelligence services such as Power BI to enrich decision-making.

Keywords for positioning: custom applications, custom software, artificial intelligence, cybersecurity, AWS and Azure cloud services, business intelligence services, AI for companies, AI agents, Power BI.

Practical summary: build the Web API in .NET 8 with a clean layered structure, implement CQRS with MediatR, validate with FluentValidation, protect routes with JWT, persist in PostgreSQL, and optimize responses with Redis. Automate with Docker and CI/CD, and complement with security and monitoring practices.

If you want Q2BSTUDIO to help you create a solid foundation for your next project, we can offer architecture auditing, custom development, AI integration for companies, implementation of AI agents, and business intelligence solutions with Power BI. Contact us for personalized consulting and a delivery plan tailored to your goals.

OUR SERVICES

How we can help you

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.