REST API Frameworks
Having used REST API frameworks such as ASP.NET Core, Spring Boot and Quarkus, I noticed that they tend to share a broadly similar execution model.
An incoming HTTP request is received and parsed into a request context. That context passes through a middleware pipeline, where each component may inspect, enrich, transform or short-circuit the request.
If processing continues, the request is routed to an endpoint handler, typically a controller action.
The handler invokes application logic and produces a response, which propagates back through the pipeline where it may undergo further processing such as logging, compression and header manipulation before being serialized and returned to the client. The implementations differ, but the underlying architectural primitives are surprisingly familiar.
I think it is good for backend developers to understand these fundamentals.
Including myself.
Client Request Pipeline
This is an abstracted view of the common components found in a modern REST API framework:
After modelling the architecture, I decided to build it.
Constraints
To explore the architecture end-to-end, I built a basic HTTP/1.1 web server and a minimal REST API framework under a deliberately restrictive set of constraints:
- absolutely no dependency on ASP.NET Core types, no HttpContext etc.
- no borrowing infrastructure such as DI/host composition, caching, etc.
- everything from scratch, including HTTP protocol, header parsing, routing, etc.
- maintainability score ≥ 80% using the Visual Studio Maintainability Index
- time-boxed to two weeks
The objective wasn't to build an alternative to ASP.NET Core.
It was to reconstruct enough of the machinery to understand how the pieces fit together.
Flame and Phoenix
The solution consisted of two console applications:
- Flame
- Phoenix
and two class libraries:
- Flame.Http
- Flame.Utilities
Flame provided a minimal HTTP implementation and REST framework.
Phoenix rose from the flame, a simple web application.
Technologies used included C# 12, .NET 8, JetBrains Rider, Visual Studio and Locust for load testing.
It's Alive!
There is something particularly satisfying about watching a web server respond to its first request:
initializing...flame is running....
server listening on port 8080
...
[1] client connection opened:
...
HTTP/1.1 200 Ok
Server: Flame/0.1
Date: Sun, 21 Apr 2024 05:44:09 UTC
Content-Type: text/html
Content-Length: 661
Connection: keep-alive
Set-Cookie: session=1; Path=/; HttpOnly; Max-Age=1200
At this point, Flame was speaking the language of the web.
The next question was how well it would behave under pressure.
Enter the Locusts
Using Locust, I wrote a custom Python script to exercise the server:
The first run used a single user to verify that requests completed without failures.
The second ramped up to 1,000 concurrent simulated users, increasing by ten users per second. Each user executed a sequence of approximately 50 HTTP requests to reproduce the ASCII-art demonstration, exercising the application's routing, command processing and session management.
Once the user count stabilised, Phoenix sustained approximately 1,100 requests per second with no reported failures. The 95th-percentile response time settled at around 1.3 seconds, while throughput remained relatively stable throughout the remainder of the test. It was interesting to observe how increasing concurrency affected response times without causing a progressive decline in throughput.
The tests were run on my development laptop, with both Locust and Phoenix competing for resources:
Locust and Phoenix used approximately the same amount of CPU, but memory was a different story:
The 10K Challenge
Several years ago, whilst working through Bryan Cairns's fantastic C++/Qt video series, I encountered his 10k concurrent connections challenge. I couldn't resist.
Phoenix reached 10,000 concurrent simulated users, but performance began to degrade at around 7,000.
Throughput initially peaked at approximately 1,300 requests per second before settling around 800-900, while response times increased significantly as concurrency grew. At 10,000 users, the 95th-percentile response time was approximately 5.8 seconds, with increasingly pronounced fluctuations thereafter.
Across 1,414,478 requests, 11,576 failed, representing a failure rate of approximately 0.82%.
The intermittent stutters may have been caused by garbage collection pauses, although I didn't investigate this further.
Clearly, there's plenty of room for improvement:
Comparing the two runs reveals an interesting distinction between throughput and response times. At 1,000 simulated users, Phoenix maintained stable throughput with no reported failures. At 10,000 users, throughput remained relatively steady, albeit at a lower rate, while response times deteriorated significantly.
The 95th-percentile (P95) response time is particularly revealing. It represents the response time within which 95% of requests complete, providing a useful indication of slower requests that an average might obscure. The comparison illustrates how a server can continue processing a substantial volume of requests even as its responsiveness declines under increasing load.
| Metric | 1,000 Users | 10,000 Users |
|---|---|---|
| Throughput | ~1,100 RPS | ~800-900 RPS |
| P95 at target user count | ~1.3 s | ~5.8 s |
| Reported failures | 0% | ~0.82% overall |
Framework Semantics
In Phoenix, we can now see the concepts emerge from the lower-level machinery in Flame. In this example, a Phoenix controller inherits from AppController and delegates to a service injected by Flame:
[Controller(Path = "/api/command/")]
public class CommandController(GraphicsService graphics) : AppController
{
[Get(Path = "fill/:x/:y")]
public string Fill(int x, int y) => graphics.Fill(Session.Canvas, x, y);
// ... other actions
}
The route expression fill/:x/:y is used by Flame to map the incoming path values to the action parameters.
By the time this method was invoked, Flame had received and parsed the HTTP request, constructed the request context, passed it through middleware, identified the route, created the controller, injected its dependencies and mapped the route values to the action parameters.
A small amount of application code was sitting on top of quite a lot of machinery.
Session and Application State
I initially built a sharded cache with expiring cache items, but later pulled back for a simpler solution so I could explore the semantics afforded by DynamicObject.
ConcurrentDictionary already provides fine-grained concurrency control internally, allowing multiple threads to access the dictionary efficiently, which is more than sufficient for this exercise. For workloads where the expected number of entries is known, specifying an initial capacity can also reduce resizing overhead during growth:
var concurrencyLevel = Environment.ProcessorCount * 2;
var initialCapacity = 100_000;
var cache = new ConcurrentDictionary<string, object?>(concurrencyLevel, initialCapacity);
Returning to the Session and Application objects, they were updated to use a dynamic object store:
public class ObjectStore : DynamicObject, IEnumerable<(string, object?)>
{
private readonly ConcurrentDictionary<string, object?> _settings
= new(StringComparer.OrdinalIgnoreCase);
// ...
}
That allowed client code to remain extremely simple:
var pen = new Pen();
Session.Pen = pen;
Session.Canvas = new Canvas(pen, width, height);
Anything could be stored in the session, with runtime interception handling access to the underlying objects.
WebApplication
I reproduced the familiar application-builder semantics found in ASP.NET Core, implementing the dependency injection container, service locator, host composition, request/response handlers, middleware pipeline and supporting infrastructure myself. None of these components depended on ASP.NET Core types or infrastructure.
Configuration and startup ultimately became:
var builder = new WebApplicationBuilder();
var app = builder.Build();
app.MapControllers();
app.Run();
Code Quality
The project remained in reasonably good shape, although Phoenix missed the maintainability target:
I wasn't particularly concerned. Phoenix was deliberately a thin consumer application; the framework machinery and architectural complexity lived in Flame.
That constraint for Flame, however, proved useful. Building infrastructure from scratch makes it very easy for implementation complexity to leak into the abstractions exposed to consumers.
Conclusion
I must say, this was fun.
I had to restrain myself from improving it, especially with the recent C#/.NET improvements.
ASP.NET Core exists, and it is fantastic. There would be little value in turning a learning exercise into an attempt to reproduce years of engineering effort embodied in a mature framework.
Building Flame and Phoenix forced me to compose the architectural primitives of a basic web server and REST API framework from first principles: transport, parsing, request contexts, middleware, dependency container, routing, controllers, state, application services, serialization and responses.
Frameworks make these things look simple.