Skip to content

Organize Minimal APIs for scale for large production Systems

Tags: ASP.NET Core, ASP.NET Minimal APIs, .NET 10, .NET Architecture, Microservices, Middleware, Dependency Injection, OpenTelemetry, Distributed Systems, Messaging, API Design, Health Checks, Observability, Resilience, Platform Engineering


Audience: Solution Architects, Principal Engineers, Lead Developers, Platform Engineers, Cloud-Native Application Teams


Technologies: ASP.NET Core, .NET 10, Minimal APIs, OpenTelemetry, Distributed Tracing, Health Checks, Dependency Injection


Summary


Minimal APIs have been around for a while now. It started out as an alternative to MVC that added a lot of ceremony, which becomes unnecessary unless we are building large scale production grade API backends upfront.


In the world of agentic coding, we often start with a small set of APIs and a lean frontend that promotes the idea and proves the capability first before building large scale capabilities to it.


Minimal APIs are perfect for that. It takes an opt-in approach that allows you to develop the functionality and validate the outcome first before adding any cross-cutting concerns, like authentication, tracing, logging and anything else that requires to be added. 


But what happens when your idea is successful and turned into a production grade application?  Feature requests keep rolling in along with concerns of maintaining a production grade system that (hopefully) won’t keep the ops engineer up at night. This is where the free-flowing coding style of minimal API can become a maintenance nightmare.


How do we fix this?


In between production releases with version upgrades and maintenance releases, we explored this very question. How do we ensure that we organize a codebase that doesn’t become unrecognizable after a few months of active development? How do we make sure the next team that takes over maintenance does not feel like they have to go on a scavenger hunt to add or tweak a feature?


We have spent years building public facing APIs hosted on azure container apps that grew organically over the years and managed to keep pace with the feature expansion expectations. The results of the above questions were a number of best practices that we followed to help maintain our codebase for over two years. In this series of blog posts, we will explore each of those practices and how it helped.


Now you may ask, in the world of agentic coding, do we really care about how we organize the APIs and the plumbing around it? Won’t AI take care of that for us anyway? Well, you will be surprised how often agents with the best of harnesses still struggles to deliver high-quality feature on a dis-organized codebase. The practices that we espouse are the ones that you can apply or teach your agents to apply on your codebase.


This article assumes you understand the basics of Minimal API and have written at least a rudimentary “Hello World” version of Minimal API.


So, where do we start?


At the beginning, laydown the file and folder structure.


While we can run an API out of one single Program.cs file, that approach does not scale. For this to happen, we need to build a mono-repo where multiple feature-oriented services can exist in folders and target separate containers for hosting and yet not have a direct dependency on each other. Here is how we will scaffold the minimal api based services:

└── 📁src
└── 📁services
└── 📁catalog
└── 📁catalog.api
├── CatalogService.cs
├── CatalogServiceDependencies.cs
├── CatalogServiceEndpoints.cs
├── ICatalogService.cs
├── Program.cs
└── 📁common-lib
└── 📁catalog.client
└── 📁catalog.model
└── 📁DTOs
├── CatalogItem.cs
└── 📁Entities
└── 📁catalog.validator
└── 📁unittests
└── 📁catalogapi.test
└── 📁catalogclient.test
└── 📁catalogmodel.test
└── 📁catalogvalidator.test
└── 📁shared-lib
└── 📁caching
└── 📁configuration
└── 📁logging
└── 📁middleware
└── 📁openapiextension
└── 📁systemprobes
└── 📁unittests

Consider the Catalog service from the above folder structure. The idea is that we can host a catalog service independent of any other services in the services folder. Here are the basic tenets we followed to build the scaffolding:


1. Use a small composition entry point 

Consider the following Program.cs file:


using MinimalApiDemo.Catalog.Api;

var builder = WebApplication.CreateSlimBuilder(args);

// Add dependnacies
builder.Services
.AddSharedServices() //Add dependnecy calls for shared libraries in shared-lib
.AddCatalogServices();

//App bootstarp
var app = builder.Build();
app.UseRouting()
.UseHttpsRedirection()
.UseStatusCodePages();

//Add system probes endpoints
app.AddSystemProbeEndpoints();

//Add API Endpoints
app.AddCatalogServiceEndpoints(); // Extension method for adding catalog endpoint

//Add Developer Settings
app.ApplySwaggerDeveloperSettings();

app.Run();

And that’s it! it looks deceptively simple because you can almost use this Program.cs as a template for the next 100 APIs and the only a handful of line would have to change. The .AddCatalogServices(); and the .AddCatalogServiceEndpoints(); are the only two service specific calls here. Rest of it is abstracted away in shared-lib.


2. Separate Routing from Business Logic

Minimal API can wire up an endpoint and run business logic right from program.cs.  But we have already established the danger of that. We do not want the code to entry point to grow unbounded. To build a codebase that is still evolving after a long time of development we would want to build conventions that shall allow a developer to know instinctively or a coding agent to infer from the convention to follow.  Below is the convention that we propose which decouples the business logic from the writing.


A “normal” and coupled endpoint will look this:


app.MapGet(“/catalog”,
[AllowAnonymous] Ok<IReadOnlyList<CatalogItem>> (
ILoggerFactory loggerFactory,
CancellationToken cancellationToken) =>
{
cancellationToken.ThrowIfCancellationRequested();

IReadOnlyList<CatalogItem> items = Array.AsReadOnly<CatalogItem>(
[
new(Guid.Parse(“00000000-0000-0000-0000-000000000001”), “Notebook”, 4.50m),
new(Guid.Parse(“00000000-0000-0000-0000-000000000002”), “Desk lamp”, 24.00m)
]);

var logger = loggerFactory.CreateLogger(nameof(CatalogServiceEndpoints));
logger.LogInformation(“Returning {ItemCount} catalog items”, items.Count);

return TypedResults.Ok(items);
})
.WithName(“GetCatalogItemsInline”)
.WithTags(“Catalog”)
.WithSummary(“Get catalog items inline”)
.WithDescription(“Returns the synthetic demo catalog directly from the handler without invoking ICatalogService.”)
.ProducesProblem(StatusCodes.Status500InternalServerError);

This has a few problems. We are coupling two concerns, responsibility of retrieving the catalog items as well as the responsibility of decorating and routing the endpoint. Over time the downstream dependencies for retrieving the items may change, the logging mechanism might change and each of those changes will touch a file with routing logic that does not change without versioning. This also makes the unit testing and mocking of the downstream services complicated as it is hard to draw a clear testing boundary; are we testing the retrieval or are we testing the routing and contract?


A decoupled Routing and Business Logic would look like this:


The CatalogServiceEndpoints.cs would have an extension method that would add the endpoint and contract:


public static WebApplication AddCatalogServiceEndpoints(this WebApplication app)
{
app.MapGet(“/catalog”, [AllowAnonymous] async Task<Ok<IReadOnlyList<CatalogItem>>> (
ICatalogService service,
CancellationToken cancellationToken) => TypedResults.Ok(await service.GetAllAsync(cancellationToken)))
.WithName(“GetCatalogItems”)
.WithTags(“Catalog”)
.WithSummary(“Get catalog items”)
.WithDescription(“Returns the synthetic items in the demo catalog.”)
.ProducesProblem(StatusCodes.Status500InternalServerError);
}

This shows nothing of the retrieval or computation logic on the endpoint wiring instructions and delegates the responsibility to ICatalogService which might look like:


public sealed class CatalogService(ILogger<CatalogService> logger) : ICatalogService
{
/// <inheritdoc/>
public async Task<IReadOnlyList<CatalogItem>> GetAllAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var catalogItems = await GetItemsAsync(cancellationToken);
logger.LogInformation(“Returning {ItemCount} catalog items”, catalogItems.Count);

return await Task.FromResult(catalogItems);
}
}

The implementation of ICatalogService can be mocked to test routing and contracts. Now we can add complexity to routing logic (conditional routing) versioned routing based on user login (as needed) and tested without ever touching the CatalogService implementation.


3. Use a Dependency Injection Convention

.NET makes it extremely easy to inject dependencies into the codebase to ensure inversion of control, testability and decoupling. But how do we make sure that dependencies are injected into the code that it is still readable and extendable by both humans and coding agents? Inside catalog.api folder we add a field designated for resolving all dependencies needed for the catalog-api to run. The CatalogServiceDependencies.cs would ideally a have two extension methods:


public static class CatalogServiceDependencies
{

/// <summary>Adds catalog services, API documentation, and problem responses.</summary>
/// <param name=”services”>The application’s service collection.</param>
/// <returns>The service collection for further registration.</returns>
public static IServiceCollection AddCatalogServices(this IServiceCollection services)
{
//Add any catalog service specific dependnacies here

services.AddScoped<ICatalogService, CatalogService>()
.AddScoped<ICatlogClient, CatalogClient>();

return services;
}

/// <summary>Reserves a registration point for future shared services.</summary>
/// <param name=”services”>The application’s service collection.</param>
/// <returns>The service collection without adding registrations.</returns>
public static IServiceCollection AddSharedServices(this IServiceCollection services)
{
//Add dependnacies from shared lib:
services.AddExceptionHandlers()
.AddHttpClient()
.AddMemoryChaching()
.AddOpenApi();

return services;
}
}

The AddCatalogServices registers any downstream dependencies specific to CatalogService and the second one AddSharedServices allows you to cherry-pick and register dependencies that are required from the shared-lib.


4. Reusable cross-cutting capabilities

Why do we have the shared-lib?  The idea is that we can have a monorepo with multiple services like catalogue that can be deployed to separate container apps and the common bits go inside the shared-lib; this helps you achieve much needed consistency while developing multiple services. It provides the same consistent and scalable way of accessing the configurations, a consistent way to report API errors using middleware, a consistent logging approach to name a few are some of the examples of code that can reside in shared-lib.  Over time you will find code in one service that can be reused in others, that’s when you would promote the shared code to shared-lib and a one liner change to the AddSharedServices would add the capability to your new service.


Note that if you are not building a monorepo structure then the shared-lib can very well be a different repo or even each subfolder of shared-lib can reside in their own repo and published through a package feed that removes close coupling and give you versioning support.  If you are deciding which way to go, my advice would be to start simple and go for versioned packages only when the size of the codebase warrants it.


Now that we know the core tenets for a minimal-api scaffolding how would it benefit agentic development?


Once you build a scaffolding like this the agent would infer the scaffolding for the next 10 (or 50) services and have the same benefits of this approach.


Also, for an agentic development workflow this scaffolding itself becomes a secondary feedback sensor. For example, when you are deploying an agent to update routing and a code change occurs in the CatalogService implementation, that would be an immediate signal that the agent is moving in the wrong direction.


You can go even further and use tools like Custom analyzers to automate and enforce some of the scaffolding rules so that the agents get instant feedback without your intervention.


This blog is an introduction in a series, that we shall publish which shall guide you through the various aspects of minimal api implementation, in terms of how to effectively leverage dependency injection, designing thin endpoint handlers, creating a reusable middleware, use logging and tracing the right way, create consistent health and readiness checks to be used across your services and also on how you can build and reuse secure and resilient http clients. Each article in this series combines implementation guidance, architectural reasoning, and production experience. The series progresses from foundational architectural concepts to addressing operational concerns.


Citation:



Related Topics

ASP.NET Core, ASP.NET Minimal APIs, .NET 10, Production-Grade ASP.NET Core, OpenTelemetry in ASP.NET Core, Distributed Tracing, CloudEvents, Event-Driven Architecture, Dependency Injection Best Practices, ASP.NET Core Middleware Architecture, Health Checks and Readiness Probes, Resilience Patterns, Secure APIs, Platform Engineering, Microservices, Distributed Systems, Azure Container Apps, Kubernetes, Enterprise Applications

Microsoft Tech Community originally posted this article on 2 December 2026 at 5:30 AM.

Leave a Reply