Advanced API Concepts and Performance

8 min read

Welcome back. By now, you have a functional ASP.NET Core API. It accepts requests and returns data. However, in the realm of software engineering, "working" is merely the baseline. The distance between a hobbyist project and an enterprise-grade system lies in how the application handles stress, enforces rules, and manages resources.

In this module, we will explore four critical pillars of a robust backend: Asynchronous Programming, Data Validation, Data Handling (Pagination), and Caching.


1. Keeping It Non-Blocking: Asynchronous Programming

Definition and Problem

In a web server, every incoming HTTP request is handled by a thread from a "thread pool."
The Problem: In a synchronous (blocking) model, when your code queries a database or calls an external API, the thread sits idle, waiting for the response. It does nothing but wait. If your server has 100 threads and receives 101 simultaneous database-heavy requests, the 101st request will hang or fail because no threads are available. This is known as Thread Pool Starvation.

The Solution: Asynchronous programming allows the thread to pause its execution and return to the pool to handle other requests while waiting for the I/O operation (Database/Network) to complete. When the operation finishes, a thread picks up where it left off.

The async and await Pattern

ASP.NET Core uses the Task-based Asynchronous Pattern (TAP). The keywords are:

  • async: Marks a method as asynchronous.
  • await: Pauses the method execution until the awaited task completes, releasing the thread.
  • Task<T>: Represents an operation that returns a value of type T in the future.

Implementation

We will modify a standard Controller action to be asynchronous.

Synchronous (Bad for I/O):

csharp
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
    // The thread is BLOCKED here while the DB works.
    var product = _context.Products.Find(id); 
    return Ok(product);
}

Asynchronous (Good for I/O):

csharp
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
    // The thread is RELEASED here.
    // It returns to the pool to help other users while the DB works.
    var product = await _context.Products.FindAsync(id); 
    return Ok(product);
}

Industry Standard 🧠:
It is best practice to propagate async all the way up from the database driver to the controller. Do not mix blocking code (.Result or .Wait()) with async code, as this can cause deadlocks.

Cancellation Tokens

In production environments, users often cancel requests (by closing the browser or navigating away). If you do not handle this, your server continues processing that heavy query uselessly.

ASP.NET Core provides a CancellationToken automatically.

csharp
[HttpGet("heavy-search")]
public async Task<IActionResult> Search(string query, CancellationToken cancellationToken)
{
    // Pass the token to the Entity Framework method
    var results = await _context.Products
        .Where(p => p.Name.Contains(query))
        .ToListAsync(cancellationToken); // Query stops if user leaves

    return Ok(results);
}

Fun Fact 🧊:
Imagine a waiter (the thread) taking an order. In a synchronous restaurant, the waiter would stand silently at the chef's table watching the soup boil for 20 minutes before serving it. In an asynchronous restaurant, the waiter puts the ticket in and serves 50 other tables while the soup cooks. Be the efficient waiter.


2. Trust No Input: Data Validation

Definition and Problem

The Problem: Users (and malicious attackers) will send invalid, incomplete, or dangerous data. Accepting a negative price for a product or an email without an "@" symbol corrupts your database integrity.

The Solution: Validation is the practice of checking input against a set of rules before processing it. If the data violates rules, the API immediately rejects the request (usually with a 400 Bad Request).

Method A: Data Annotations (Built-in)

For simple checks, ASP.NET Core provides attributes in the System.ComponentModel.DataAnnotations namespace. You decorate your DTO (Data Transfer Object) properties.

csharp
public class CreateProductDto
{
    [Required]
    [StringLength(100, MinimumLength = 3)]
    public string Name { get; set; }

    [Range(0.01, 10000)]
    public decimal Price { get; set; }

    [EmailAddress]
    public string SupportEmail { get; set; }
}

Because our controller is decorated with [ApiController], the framework automatically checks these rules. If validation fails, it prevents the action method from running and returns a JSON error response.

Method B: FluentValidation (Industry Standard)

For complex logic (e.g., "Field A is required only if Field B is X"), attributes become messy. FluentValidation is a popular .NET library that separates validation logic from the model class.

Step 1: Installation

bash
dotnet add package FluentValidation.AspNetCore

Step 2: Create a Validator

csharp
using FluentValidation;

public class ProductValidator : AbstractValidator<CreateProductDto>
{
    public ProductValidator()
    {
        RuleFor(x => x.Name).NotEmpty().Length(3, 100);
        
        RuleFor(x => x.Price)
            .GreaterThan(0)
            .WithMessage("Price must be real money.");

        // Complex logic example
        RuleFor(x => x.DiscountedPrice)
            .LessThan(x => x.Price)
            .When(x => x.IsOnSale);
    }
}

Step 3: Registration (Program.cs)

csharp
using FluentValidation;
using FluentValidation.AspNetCore;

builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<ProductValidator>();

Imagination Corner 🛡️:
Think of Validation as a bouncer at an exclusive club. Data Annotations are the dress code sign outside (No Shoes, No Shirt, No Service). FluentValidation is the bouncer who checks your ID, realizes it's fake because the birth year is 2050, and politely escorts you to the curb.


3. Handling Big Data: Pagination and Filtering

Definition and Problem

The Problem: If your database has 1,000,000 products and you call GET /api/products, your API attempts to serialize all 1 million rows into JSON. This results in:

  1. Out of Memory Exception: The server crashes.
  2. Network Latency: The client waits 30 seconds for a 50MB file.

The Solution: Pagination (sending data in chunks) and Filtering (sending only relevant data).

Deferred Execution

The key to performance here is Deferred Execution using IQueryable. We build the query in C# memory, but we do not execute the SQL command until the very last moment.

Implementing Pagination

We use Skip (ignore the first X items) and Take (grab the next Y items).

csharp
[HttpGet]
public async Task<IActionResult> GetProducts(
    [FromQuery] int pageNumber = 1, 
    [FromQuery] int pageSize = 10,
    [FromQuery] string? category = null)
{
    // 1. Start with IQueryable (No DB call yet)
    var query = _context.Products.AsQueryable();

    // 2. Apply Filtering
    if (!string.IsNullOrEmpty(category))
    {
        query = query.Where(p => p.Category == category);
    }

    // 3. Apply Pagination
    // Formula: Skip (PageNumber - 1) * PageSize
    var pagedData = await query
        .Skip((pageNumber - 1) * pageSize)
        .Take(pageSize)
        .ToListAsync(); // SQL is finally executed here

    return Ok(pagedData);
}

Metadata

In a real-world scenario, the client needs to know the total number of pages. You typically return an object wrapper:

json
{
  "data": [ ... ],
  "meta": {
    "totalRecords": 100,
    "pageNumber": 1,
    "pageSize": 10,
    "totalPages": 10
  }
}

To achieve this, you execute a .CountAsync() on the query before applying Skip/Take, then execute the fetch.

Interesting Fact 📜:
Google Search is the most famous example of pagination. Imagine if you searched for "Cats" and Google tried to load all 8 billion results on a single page. Your browser would likely melt. They Take(10) and wait for you to click "Next".


4. Speed It Up: Response Caching Basics

Definition and Problem

The Problem: Some data changes rarely (e.g., a list of Countries or Product Categories). If 1,000 users request the list of Countries, querying the database 1,000 times for the exact same static data is a waste of computing power.

The Solution: Caching. We store the result of the first request in memory. Subsequent requests get the copy, bypassing the database entirely.

Client-Side Caching (Response Headers)

The simplest form. We tell the browser to save the data.

csharp
[HttpGet("categories")]
[ResponseCache(Duration = 60)] // Cache for 60 seconds
public IActionResult GetCategories()
{
    return Ok(_repository.GetCategories());
}

This adds a Cache-Control: public,max-age=60 header. The browser won't even ask the server again for 1 minute.

Server-Side In-Memory Caching

Sometimes we need the server to hold the data (to share between different users). We use IMemoryCache.

Step 1: Registration (Program.cs)

csharp
builder.Services.AddMemoryCache();

Step 2: Implementation

csharp
public class ProductController : ControllerBase
{
    private readonly IMemoryCache _cache;
    private readonly AppDbContext _context;

    public ProductController(IMemoryCache cache, AppDbContext context)
    {
        _cache = cache;
        _context = context;
    }

    [HttpGet("popular")]
    public async Task<IActionResult> GetPopularProducts()
    {
        string cacheKey = "popular_products";

        // Check if data is in cache
        if (!_cache.TryGetValue(cacheKey, out List<Product> products))
        {
            // Data not in cache. Fetch from DB.
            products = await _context.Products.Where(p => p.IsPopular).ToListAsync();

            // Set cache options
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) // Expire in 5 mins
                .SetSlidingExpiration(TimeSpan.FromMinutes(2)); // Or if accessed, extend life

            // Save to cache
            _cache.Set(cacheKey, products, cacheEntryOptions);
        }

        return Ok(products);
    }
}

Tone Check ⚡:
Caching is powerful, but remember the old programmer saying: "There are only two hard things in Computer Science: cache invalidation and naming things." If you cache data that changes frequently (like stock prices), you serve stale data. Use caching strictly for read-heavy, low-change data.


Summary

You have elevated your API from "functional" to "professional."

  1. Async/Await ensures your server handles high traffic without blocking threads.
  2. Validation ensures only clean data enters your system using Data Annotations or FluentValidation.
  3. Pagination protects your server memory and network bandwidth.
  4. Caching reduces database load for repetitive requests.

References & Further Reading

Challenge

Task

You are provided with a boilerplate ProductsController. Your task is to refactor and enhance it to meet enterprise-grade standards by implementing asynchronous operations, data validation, pagination, and server-side caching.

Requirements

  1. Asynchronous Pagination Endpoint:

    • Convert the GetProducts method to be fully asynchronous, returning a Task<IActionResult>.
    • The method must accept two integer query parameters: pageNumber (default 1) and pageSize (default 10).
    • It must also accept a CancellationToken to support request cancellation.
    • Implement pagination logic using Skip() and Take() on the mock data source to return the correct subset of products.
  2. Data Transfer Object (DTO) and Validation:

    • Create a CreateProductDto class with the following properties: Name (string), Description (string), and Price (decimal).
    • Apply data annotation attributes to enforce these validation rules:
      • Name: Required, maximum length of 100 characters.
      • Description: Maximum length of 500 characters.
      • Price: Required, must be a value between 0.01 and 10000.
  3. Asynchronous Creation Endpoint:

    • Implement the CreateProduct method as a POST endpoint.
    • It must be asynchronous, returning a Task<IActionResult>.
    • It should accept the CreateProductDto from the request body.
    • On successful creation (simulated), it should return a CreatedAtAction response pointing to a non-existent GetProductById action (for demonstration purposes) with the new product's ID.
  4. Server-Side Caching:

    • Inject IMemoryCache into the ProductsController via its constructor.
    • In the GetProducts method, implement the cache-aside pattern:
      • Generate a unique cache key based on the pageNumber and pageSize.
      • Attempt to retrieve the paginated list of products from the cache using this key.
      • If the data is found in the cache (cache hit), return it immediately.
      • If the data is not in the cache (cache miss), retrieve it from the mock data source, store it in the cache with a 5-minute absolute expiration, and then return it.

Expected result

Your final code should contain a ProductsController that has been fully refactored according to the requirements.

  1. The ProductsController must have a private IMemoryCache field initialized through constructor injection.
  2. The GetProducts method signature must be public async Task<IActionResult> GetProducts([FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10, CancellationToken cancellationToken = default).
  3. Inside GetProducts, there must be logic to check the IMemoryCache for an existing entry. If a cache miss occurs, it should query the _products list using Skip((pageNumber - 1) * pageSize).Take(pageSize), store the result in the cache with a defined expiration, and then return the result.
  4. The CreateProductDto class must be defined with Name, Description, and Price properties, each decorated with the specified [Required], [StringLength], and [Range] data annotations.
  5. The CreateProduct method must be decorated with [HttpPost], have a signature of public async Task<IActionResult> CreateProduct([FromBody] CreateProductDto productDto), and return a CreatedAtAction result upon completion.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.