Respond to web requests during application warmup on Azure

Viewed 114

I have a web application powered by .NET 5 that is hosted on Azure. My app has quite a long warmup phase. I want my application to start responding to requests only after all the logic behind the warmup is executed. On the other hand I want to respond to http requests even before warmup to inform user that it's warming up. A line of code for a thousand words. This I want to serve when my app is warming up:

public sealed class PreStartup
{
    private static readonly DateTimeOffset Started = DateTimeOffset.UtcNow;
    
    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (httpContext, _) => await httpContext.Response.WriteAsync($"Application has been warming up for {(DateTimeOffset.UtcNow - Started):g} now"));
    }
}

And the entry point to my app looks something like this:

public static async Task Main()
{
    IConfiguration configuration = BuildConfiguration();
    
    IWebHost preHost = CreatePreWebHost(); // this guy responds to web requests before the app is warmed-up
    using IWebHost host = CreateWebHost(configuration); // this guy is my primary web host
    
    try
    {
        _ = preHost.StartAsync(); // start the pre host in a non-blocking manner
        await WarmupAsync(); // and proceed with the warmup (this takes long)
    }
    finally
    {
        await preHost.StopAsync(); // warmup is finished and the pre host is no longer needed - stop and dispose
        preHost.Dispose();
    }

    await host.RunAsync(); // the primary host takes over
}

The solution works perfectly when running it locally on my machine. Problems start when deployed to Azure. The App Service restarts the application as soon as pre host is disposed and the primary host never takes over. Is there a way to swap the web host when the application is running?

0 Answers
Related