Sobes.tech
Junior — Middle

Can you give an example of using an intermediate layer to estimate the processing duration of each request?

sobes.tech AI

Answer from AI

Middleware for estimating request processing duration is often implemented by intercepting the call and measuring the time before and after processing.

Example in C# using ASP.NET Core middleware:

public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestTimingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();

        await _next(context); // pass control to the next component

        stopwatch.Stop();
        var elapsedMs = stopwatch.ElapsedMilliseconds;

        Console.WriteLine($"Request [{context.Request.Method}] {context.Request.Path} took {elapsedMs} ms.");
    }
}

// In Startup.cs or Program.cs, add the middleware:
// app.UseMiddleware<RequestTimingMiddleware>();

This middleware measures the processing time of each HTTP request and outputs the result to the console. This approach helps monitor performance and identify bottlenecks.

Can you give an example of using an intermediate… - sobes.tech