Wijitha
Wijitha

Reputation: 1389

Prevent IIS from Idle Timeout when Running Background Tasks

In our ASP.Net Core Web API, we have used Hosted Services to perform some background tasks. Sometimes it is possible that these background tasks to take a long time to complete (about an hour). Everything works seamlessly except when there are long-running tasks.

IIS Application Pool's default value for Idle Timeout is 20 mins. So when there is no request for 20 mins, IIS restarts the application pool. But sometimes it is possible that a background task running and IIS restarts irrespective of it causing tasks to terminate abruptly without marking it complete. As soon as IIS starts, tasks are picked up again by the hosted service start processing. But before completing, IIS restarts and this can go on forever. This can cause lots of issues when there are email sending tasks where same email can be potentially sent multiple times.

Since Hosted services are a first-class citizen of ASP.NET Core, It would be ideal if IIS considers background executions as well when performing idle timeouts.

Right now we have overcome this issue by setting Idle Timeout to 0 so that it never timeout. That's a kind of hacky solution. Also, it's not a viable option in load-balanced environments where nodes are adding and removing dynamically.

Is there a better way to "Prevent IIS from restarting while a background execution is in progress"?

Thanks

Upvotes: 12

Views: 13345

Answers (2)

salli
salli

Reputation: 782

Consider using Hangfire designed for such tasks. For the time being, You can configure your IIS to always run the site.

  1. Right-click site name > Manage WebSite > Advance > make sure preload is set to true.

  2. Right-click app pool > advance settings > Idle Time-out (minutes) to 0 and Start Mode to always running.

Upvotes: 15

Jonathan Busuttil
Jonathan Busuttil

Reputation: 493

I do not know your setup, but maybe you omit IIS and use something such as Kestrel.

Also, I would not put very long running tasks such as sending emails to run in an IIS process. Rather put the in another process such as a console app and leave the apsnetcore app to serve requests to the user.

Upvotes: 2

Related Questions