Search code examples
.net-corexamarin.androidkestrel

How to ensure API is "warmed up" before first request?


I have a xamarin android app that makes requests to an api hosted on .net core (on IIS on Windows Server). Initial requests ALWAYS take a long time to load (presumably because of some warmup process). How do I ensure that the API is ready to go by the time the user needs to make a request?

Do I just make rapid async get/post requests on app startup? This seems in-efficient...


Solution

  • You need to use health check for your API:

    public class ExampleHealthCheck : IHealthCheck
    {
        public ExampleHealthCheck()
        {
            // Use dependency injection (DI) to supply any required services to the
            // "warmed up" check.
        }
    
        public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
             CancellationToken cancellationToken = default(CancellationToken))
        {
            // Execute "warmed up" check logic here.
    
            var healthCheckResultHealthy = true;
    
            if (healthCheckResultHealthy)
            {
                return Task.FromResult(
                HealthCheckResult.Healthy("The check indicates a healthy result."));
            }
    
            return Task.FromResult(
            HealthCheckResult.Unhealthy("The check indicates an unhealthy result."));
        }
    }
    

    Add your service to health check services:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks()
            .AddCheck<ExampleHealthCheck>("example_health_check");
    }
    

    In Startup.Configure, call UseHealthChecks in the processing pipeline with the endpoint URL:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseHealthChecks("/health");
    }
    

    Link to documentation: https://learn.microsoft.com/ru-ru/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-2.2