C# Interview Question #197

How would you make an external API call reliable in a production C# application?

Senior .NET Practical Scenarios Senior Advanced

Quick Interview Answer

Use HttpClient through IHttpClientFactory or another managed client strategy instead of creating and disposing a new HttpClient for every request.

Detailed Explanation

Use HttpClient through IHttpClientFactory or another managed client strategy instead of creating and disposing a new HttpClient for every request.

Set appropriate timeouts and propagate CancellationToken. Handle transient failures with carefully designed retries, but only when the operation is safe to retry. Exponential backoff and jitter can prevent synchronized retry storms.

Consider circuit breaking, rate limits, idempotency, authentication-token management, structured logging, metrics, distributed tracing, and validation of external responses.

Reliability policies should match the semantics of the remote operation; automatically retrying a non-idempotent payment request can be dangerous.

Code Example

builder.Services.AddHttpClient<IWeatherClient, WeatherClient>(
    client =>
    {
        client.BaseAddress =
            new Uri("https://api.example.com/");
        client.Timeout = TimeSpan.FromSeconds(10);
    });