I am developing an API web server using C# Minimal APIs and encountered a performance issue related to API latency.
In my specific case, I have a server hosted in Europe, while the client is located in Latin America. When I ping the server from the client, I observe a latency of approximately 235-245 ms. This latency represents the theoretical lower limit of my API’s response time, and I would like to get as close to this limit as possible.
Here are the results I measured:
Client-Side Response Time: ~530-540 ms
Server-Side Execution Time: ~20 ms
Given this, I expected the total response time to be approximately 260-290 ms:
Latency (~240 ms) + Server Execution Time (~20 ms) + a few milliseconds for data transfer (since the response data is minimal).
However, the actual client-side response time is significantly higher than expected, leading me to suspect an additional round-trip that might be doubling the latency:
Latency (240 ms) x 2 + Server Execution Time (20 ms) ≈ +500 ms
After thorough debugging, I discovered that the use of the [FromBody] attribute on my endpoint method seems to be causing this additional latency.
Here are two code examples for comparison:
// This method executes in ~530ms from the client
app.MapPost("/Test1", (HttpContext context, [FromBody] BodyTest inputParameters) =>
{
return "test";
})
.WithOpenApi();
// This method executes in ~240ms from the client
app.MapPost("/Test2", (HttpContext context) =>
{
return "test";
})
.WithOpenApi();
The presence of the [FromBody] parameter significantly increases the response time (~530 ms). Even when the parameter is not provided in the request, the increased response time persists, ruling out data transfer as the cause.
This latency issue obviously disappear when woking in the same LAN of the server, where i get response times of about 30ms
Any ideas of what the root cause could be and how to fix it?
1