惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V2EX - 技术
V2EX - 技术
L
LangChain Blog
IT之家
IT之家
S
SegmentFault 最新的问题
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
U
Unit 42
B
Blog RSS Feed
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
C
CERT Recently Published Vulnerability Notes
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
Vercel News
Vercel News
S
Schneier on Security
Spread Privacy
Spread Privacy
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 叶小钗
雷峰网
雷峰网
博客园_首页
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog
The Hacker News
The Hacker News
T
Tor Project blog
L
Lohrmann on Cybersecurity
Know Your Adversary
Know Your Adversary
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy International News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tenable Blog
V
Vulnerabilities – Threatpost
大猫的无限游戏
大猫的无限游戏
博客园 - 【当耐特】
V
V2EX
Security Latest
Security Latest
A
About on SuperTechFans
Cloudbric
Cloudbric
S
Security Affairs
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
TaoSecurity Blog
TaoSecurity Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Claprec: Inside the Architecture - N-Tier, decoupling, microservices (2/6)
Kenan Sejmen · 2026-05-13 · via DEV Community

Series Roadmap

  • Product Overview (1/6)
  • Architecture: N-Tier Design, Decoupling, and Microservices (2/6)
  • Frontend: Angular SSR, NgRx, and OpenAPI Integration (3/6)
  • Machine Learning in Practice (4/6)
  • Database Design and Data Modeling (5/6)
  • Engineering Tradeoffs: Limited Time vs. Ideal Architecture (6/6)

System Architecture Overview

The application is deployed within a Dockerized environment consisting of six containers:

  • 3 Backend Microservices: API (the main one), Real-time, and Views-processing.
  • 1 Frontend Container.
  • Infrastructure: Microsoft SQL Server (MSSQL) and RabbitMQ message broker.

To visualize the backend architecture, the following animation illustrates the layers and some of their dependencies.

This article focuses specifically on the architectural decisions and patterns implemented within the backend microservices.


Main Microservice

The main microservice acts as the primary backend service. It follows an N-Tier Architecture, where the depth of the stack varies based on the complexity of the functionality being implemented.

Architectural Layers

To ensure strict Separation of Concerns (SoC) and adherence to the DRY (Don't Repeat Yourself) principle, the architecture defines three distinct stack depths:

  • Entity Mutations / CRUD (8 Layers):
    Higher CRUD Controller -> Base Higher CRUD Controller -> Service -> Base Higher CRUD Service -> Validation -> BusinessRule -> Base Service -> Repository

  • Database-Stored Enums (6 Layers):
    Db Enum Controller -> Base Db Enum Controller -> Service -> Base Db Enum Service -> Base Service -> Repository

  • Generic Functionality (4 Layers):
    Controller -> Service -> Base Service -> Repository

The "HigherCrud" System: Solving Multiple Inheritance

Entities often share common behaviors: existence checks, validation logic, and standard business rules. Ideally, this would be implemented via multiple inheritance.

However, C# does not support multiple class inheritance, unlike C++.

To compose shared behaviors with a minimal code duplication, I implemented a solution inspired by Unix file permissions (bitwise flags).

The Bitwise Controller Hierarchy

I categorized CRUD operations into "Pure" base controllers, assigning each a specific level (bit value):

  • Level 0 (ReadBasic): GET paginated list and GET specific entity.
  • Level 1 (ReadCalculated): Inherits Level 0 + more extensive GET endpoint for calculated properties.
  • Level 2 (Delete): Inherits Level 0 + DELETE endpoint (includes existence checks).
  • Level 4 (Create): Inherits Level 0 + POST endpoint (includes validation).
  • Level 8 (Update): Inherits Level 0 + PATCH endpoint (includes existence checks and validation).
// Level0AbstractHigherCrudController.cs

// Level 0 (Read Basic)

public abstract class Level0AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch> :
    AbstractBaseHigherCrudController,
    ILevel0AbstractHigherCrudController<TDtoPlain, TDtoRelated, TPrimaryKey, TSearch>
    where T : class
    where TDtoPlain : class
    where TDtoRelated : TDtoPlain
    where TSearch : BaseSearchDto
{
    private readonly ILevel0AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch> _baseHigherCrudServiceLevel0;

    protected Level0AbstractHigherCrudController(ILevel0AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch> baseHigherCrudServiceLevel0)
    {
        _baseHigherCrudServiceLevel0 = baseHigherCrudServiceLevel0;
    }

    [SwaggerOperation("Level 0", "Get paginated entities")]
    [HttpGet]
    [SwaggerResponse(StatusCodes.Status200OK)]
    [SwaggerResponse(StatusCodes.Status204NoContent)]
    public virtual async Task<ActionResult<PaginatedResponse<TDtoRelated>>> Get([FromQuery] TSearch search)
    {
        return await _baseHigherCrudServiceLevel0.GetPaginated(search, FormReqURLBuilder());
    }

    [SwaggerOperation("Level 0", "Get an entity")]
    [HttpGet(GET_BY_ID_ROUTE)]
    [SwaggerResponse(StatusCodes.Status200OK)]
    [SwaggerResponse(StatusCodes.Status404NotFound, Type = typeof(DtoError))]
    public virtual async Task<ActionResult<TDtoRelated>> GetById(TPrimaryKey id)
    {
        return await _baseHigherCrudServiceLevel0.GetById(id);
    }
}

Enter fullscreen mode Exit fullscreen mode

// Level1AbstractHigherCrudController.cs

// Level 1 (Read Calculated)

public abstract class Level1AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TDtoCalculated, TPrimaryKey, TSearch> :
    Level0AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch>,
    ILevel1AbstractHigherCrudController<TDtoPlain, TDtoRelated, TDtoCalculated, TPrimaryKey, TSearch>
    where T : class
    where TDtoPlain : class
    where TDtoRelated : TDtoPlain
    where TDtoCalculated : TDtoPlain
    where TSearch : BaseSearchDto
{
    private readonly ILevel1AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TDtoCalculated, TPrimaryKey, TSearch> _level1AbstractBaseHigherCrudService;

    protected Level1AbstractHigherCrudController(ILevel1AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TDtoCalculated, TPrimaryKey, TSearch> level1AbstractBaseHigherCrudService)
        : base(level1AbstractBaseHigherCrudService)
    {
        _level1AbstractBaseHigherCrudService = level1AbstractBaseHigherCrudService;
    }

    [SwaggerOperation("Level 1", "Get an entity (detailed)")]
    [HttpGet(GET_CALCULATED_BY_ID_ROUTE)]
    [SwaggerResponse(StatusCodes.Status200OK)]
    [SwaggerResponse(StatusCodes.Status404NotFound, Type = typeof(DtoError))]
    public virtual async Task<ActionResult<TDtoCalculated>> GetCalculatedById(TPrimaryKey id)
    {
        return await _level1AbstractBaseHigherCrudService.GetCalculatedById(id);
    }
}

Enter fullscreen mode Exit fullscreen mode

// Level2AbstractHigherCrudController.cs

// Level 2 (Delete)

public abstract class Level2AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch> :
    Level0AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch>,
    ILevel2AbstractHigherCrudController<TDtoPlain, TDtoRelated, TPrimaryKey, TSearch>
    where T : class
    where TDtoPlain : class
    where TDtoRelated : TDtoPlain
    where TSearch : BaseSearchDto
{
    private readonly ILevel2AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch> _level2AbstractBaseHigherCrudService;

    protected Level2AbstractHigherCrudController(ILevel2AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch> level2AbstractBaseHigherCrudService)
        : base(level2AbstractBaseHigherCrudService)
    {
        _level2AbstractBaseHigherCrudService = level2AbstractBaseHigherCrudService;
    }

    [SwaggerOperation("Level 2", "Delete an entity")]
    [HttpDelete(REMOVE_BY_ID_ROUTE)]
    [SwaggerResponse(StatusCodes.Status200OK)]
    [SwaggerResponse(StatusCodes.Status404NotFound, Type = typeof(DtoError))]
    public virtual async Task RemoveById(TPrimaryKey id)
    {
        await _level2AbstractBaseHigherCrudService.RemoveById(id);
    }
}

Enter fullscreen mode Exit fullscreen mode

// Level4AbstractHigherCrudController.cs

// Level 4 (Create)

public abstract class Level4AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TInsert, TInsertValidation> :
    Level0AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch>,
    ILevel4AbstractHigherCrudController<TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TInsert>
    where T : class
    where TDtoPlain : class
    where TDtoRelated : TDtoPlain
    where TSearch : BaseSearchDto
{
    private readonly ILevel4AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TInsert> _level4AbstractBaseHigherCrudService;

    protected Level4AbstractHigherCrudController(ILevel4AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TInsert> level4AbstractBaseHigherCrudService)
        : base(level4AbstractBaseHigherCrudService)
    {
        _level4AbstractBaseHigherCrudService = level4AbstractBaseHigherCrudService;
    }

    [SwaggerOperation("Level 4", "Create an entity")]
    [HttpPost]
    [SwaggerResponse(StatusCodes.Status200OK)]
    [SwaggerResponse(StatusCodes.Status400BadRequest, Type = typeof(List<DtoValidationError>))]
    [SwaggerResponse(StatusCodes.Status422UnprocessableEntity, "Unprocessable Entity", typeof(List<DtoValidationError>))]
    public virtual async Task<ActionResult<TDtoPlain>> Insert([FromBody] TInsert insert)
    {
        return await _level4AbstractBaseHigherCrudService.Insert(insert);
    }
}

Enter fullscreen mode Exit fullscreen mode

// Level8AbstractHigherCrudController.cs

// Level 8 (Update)

public abstract class Level8AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TUpdate, TUpdateValidation> :
    Level0AbstractHigherCrudController<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch>,
    ILevel8AbstractHigherCrudController<TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TUpdate>
    where T : class
    where TDtoPlain : class
    where TDtoRelated : TDtoPlain
    where TSearch : BaseSearchDto
{
    private readonly ILevel8AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TUpdate> _level8AbstractBaseHigherCrudService;

    protected Level8AbstractHigherCrudController(ILevel8AbstractBaseHigherCrudService<T, TDtoPlain, TDtoRelated, TPrimaryKey, TSearch, TUpdate> level8AbstractBaseHigherCrudService)
        : base(level8AbstractBaseHigherCrudService)
    {
        _level8AbstractBaseHigherCrudService = level8AbstractBaseHigherCrudService;
    }

    [SwaggerOperation("Level 8", "Update an entity")]
    [HttpPatch(UPDATE_BY_ID_ROUTE)]
    [SwaggerResponse(StatusCodes.Status200OK)]
    [SwaggerResponse(StatusCodes.Status400BadRequest, Type = typeof(List<DtoValidationError>))]
    [SwaggerResponse(StatusCodes.Status404NotFound, Type = typeof(DtoError))]
    [SwaggerResponse(StatusCodes.Status422UnprocessableEntity, "Unprocessable Entity", typeof(List<DtoValidationError>))]
    public virtual async Task<ActionResult<TDtoPlain>> UpdateById(TPrimaryKey id, [FromBody] TUpdate update)
    {
        return await _level8AbstractBaseHigherCrudService.UpdateById(id, update);
    }
}

Enter fullscreen mode Exit fullscreen mode

Composing Controllers

Developers can inherit directly from "Pure" controllers for simple endpoints. By summing these values, we create "Mix" controllers that combine functionalities. A specific entity controller simply inherits from the appropriate Mix base class.

  • Example: An entity requiring ReadBasic (0), Create (4) and Delete (2) functionality inherits from Level 6.
  • Full CRUD: An entity requiring all operations inherits from Level 15 (0+1+2+4+8).
Implementation Logic

Since C# does not support multiple inheritance, we cannot simply inherit Level2 and Level4 simultaneously to create Level6. Instead, the "Mix" classes pre-chain the inheritance hierarchy to simulate this composition.

For example, Level 13 (Update + Create + Read Calculated + Read Basic) is implemented by inheriting from Level 5, which in turn inherits from Level 1, which inherits from Level 0. This linear chain aggregates the features cumulatively:

  • Level 0 provides ReadBasic capabilities
  • Level 1 inherits Level 0 (ReadBasic) and adds ReadCalculated capabilities.
  • Level 5 inherits Level 1 and adds Create capabilities.
  • Level 13 inherits Level 5 and adds Update capabilities.

Admittedly, this approach requires pre-defining these specific "Mix" classes in the base library, resulting in a certain degree of code duplication within the foundational layer. However, this is a necessary compromise to bypass the language's constraints. It is a trade-off that pays off significantly in Developer Experience (DX). The result is an elegant and intuitive interface: developers simply inherit from the specific "Level" class they desire, and the complex composition of behaviors is handled automatically.

Service Layer & Extensibility

The Service Layer mirrors the controller hierarchy precisely, ensuring that every "Level" in the API stack has a corresponding logical backbone (Base Higher CRUD Service). This parallel structure handles the validation pipeline, business rules and other concerns.
To ensure flexibility, the architecture relies on polymorphism: core operations are implemented as virtual methods, allowing an override of specific behaviors - such as injecting custom logic before a save - without disrupting the inheritance chain.
Furthermore, if an entity requires functionality outside the standard CRUD scope, the solution is intuitive: simply define a new method in the Controller and a corresponding one in the Service, effortlessly adding the required custom functionality.

Practical Example: "Product" Entity

To implement full CRUD for a "Product" entity:

  1. Inherit HigherBaseCrudController (Level 15).
  2. Inherit HigherBaseCrudService (Level 15).
  3. Define Format and Business Rule Validators.
  4. Define DTOs.
// ProductController.cs

[ApiController]
[Route("")]
public class ProductController :
    Level15AbstractHigherCrudController<Product, DtoPlainProduct, DtoRelatedProduct, DtoCalculatedProduct, long, SearchDtoProduct, InsertDtoProduct, UpdateDtoProduct, IAbstractValidation<InsertDtoProduct>, IAbstractValidation<UpdateDtoProduct>>
{
    private readonly IHigherCrudServiceProduct _higherCrudServiceProduct;

    public ProductController(
        IHigherCrudServiceProduct higherCrudServiceProduct
    ) : base(higherCrudServiceProduct)
    {
        _higherCrudServiceProduct = higherCrudServiceProduct;
    }

    // ...
}

Enter fullscreen mode Exit fullscreen mode

Result: The system scaffolds 6 endpoints automatically (3 GET, 1 POST, 1 DELETE, 1 PATCH).

Validation Pipeline

The validation layer optimizes resource usage by preventing unnecessary database calls.

  1. Format Validator: Checks data constraints (e.g., string length < 255). Returns HTTP 400 on failure.
  2. Business Rule Validator: Checks database constraints (e.g., unique email). Returns HTTP 422 on failure.

Optimization:

  • If Format Validation fails, the pipeline short-circuits, and Business Rule Validation (DB hit) is skipped.
  • Business Rule Validation fails fast (returns immediately on first error) to minimize DB load.
  • Error responses share a unified interface, simplifying frontend error parsing.
// AbstractValidation.cs

public abstract class AbstractValidation<T> : IAbstractValidation<T>
{
    private readonly List<IValidatorWithException<T>> _validators = new();

    public async Task Validate(T t)
    {
        foreach (var validator in _validators)
        {
            var validationResult = await validator.ValidateAsync(t);

            if (!validationResult.IsValid)
            {
                validator.ThrowException(validationResult.Errors);
            }
        }
    }

    protected void AddValidatorsInOrder(params IValidatorWithException<T>[] validators)
    {
        foreach (var validator in validators)
        {
            _validators.Add(validator);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

// AbstractFormatValidatorWithException.cs

public abstract class AbstractFormatValidatorWithException<T> : AbstractValidator<T>, IFormatValidatorWithException<T>
{
    void IValidatorWithException<T>.ThrowException(List<ValidationFailure> validationFailures)
    {
        throw new ValidationException(validationFailures);
    }
}

Enter fullscreen mode Exit fullscreen mode

// AbstractBusinessRuleValidatorWithException.cs

public abstract class AbstractBusinessRuleValidatorWithException<T> : AbstractValidator<T>, IBusinessRuleValidatorWithException<T>
{
    protected AbstractBusinessRuleValidatorWithException()
    {
        RuleLevelCascadeMode = CascadeMode.Stop;
    }

    void IValidatorWithException<T>.ThrowException(List<ValidationFailure> validationFailures)
    {
        throw new BusinessRuleException(validationFailures);
    }
}

Enter fullscreen mode Exit fullscreen mode

Data Mapping & API Standards

AutoMapper & PATCH Semantics:
Implementing partial updates (PATCH) with AutoMapper presents a challenge: distinguishing between an intentional null update and an ignored field.

  • Scenario: An entity has an optional description. Updating it to null (to clear it) is indistinguishable from "do not update" if AutoMapper ignores nulls.
  • Solution: Manual mapping is used for specific edge cases to ensure correctness. Alternatively, switching to PUT (full replacement) solves the ambiguity but increases payload size.

Infrastructure:

  • Swagger: Configured with versioning and Bearer JWT authentication (including session tracking).
  • Database Enums: Enums are defined in a dedicated backend layer for seeding, storing byte IDs, and rendering string values (prettified for UI).
  • SMTP: Email sending is handled by a thread-safe background service (Queue-based) to prevent SMTP failures during concurrent requests.
  • NSFW filter: Applied to publicly visible media; skipped for private uploads (e.g., identity verification).

Testing & Performance

The backend includes Unit and Integration tests.

  • Performance Optimization: Integration test execution time was reduced by 91.1% (from 8.3 minutes to 44.2 seconds). A detailed IEEE-format breakdown is available here.

Views-Processing Microservice

This microservice is designed for data analytics and post-processing.

  • Event-Driven: Listens for view events thrown by the Main microservice via RabbitMQ.
  • Data Storage: Persists metadata (creation date, user ID, entity ID, IP address etc.) into a dedicated MSSQL database.
  • Purpose: Aggregates engagement data (views on businesses, products, reviews, comments) for analytical insights.

Real-Time Microservice

Built on SignalR, this microservice manages live connectivity and user presence with a strong focus on resource optimization.

Performance & Resource Management

  • Memory Footprint: Optimized to utilize 300-350MB of RAM for 5,000+ concurrent users during stress tests.
  • User Presence: Activity status is stored as a bit flag in the relational database.
  • Storage: Uses ConcurrentDictionary (static in-memory) for connection management, resolving thread-safety issues encountered with standard dictionaries.
// ChatHub.cs

// user.Id, dictionary of: connectionId, listenToUserId
private static readonly ConcurrentDictionary<long, ConcurrentDictionary<string, long>> _connectedUsersForIndividualChat = new();

Enter fullscreen mode Exit fullscreen mode

Resilience Strategy

Because state is stored in RAM, service failure leads to temporary incoherent IsActive status.

  • Solution: Rather than implementing complex snapshot persistence, the system relies on the frontend's auto-retry connection strategy. Upon reconnection, the state self-corrects. This trades temporary inconsistency for implementation simplicity and lower overhead.

Bandwidth Optimization

To minimize WebSocket traffic:

  • Counts vs. Payloads: Only unread notification/chat counts are pushed to clients, not the full objects.
  • Chat Messages: Messages are only exchanged live when a user explicitly joins a specific chat room.
  • Queue Management: No message accumulation occurs when a user is disconnected; counts update only upon connection.

Architecture

  • Repository pattern: Uses Entity Framework via the Repository pattern for data access.
  • Integration: consumes RabbitMQ events from the main microservice (e.g., new notifications for: replies, reviews etc.).

What's Next

With the backend architecture solidly in place - from N-Tier layers to bitwise CRUD composition - the foundation is set. Next, we'll shift to the client side.

Join me in Claprec: Frontend - Angular, NgRx, and OpenAPI (3/6), where I transition from Next.js to Angular's opinionated structure. We will tackle complex challenges including real-time chat scroll management, architecting reusable pagination, handling recursive state with NgRx, and enforcing type safety via Contract-First Design.


Questions or thoughts on the architecture? Drop a comment - I'd love to hear!