How to prevent ASP.Net api from going to sleep

Web Api is a framework to build HTTP based services, especially RESTful apis. It is designed to build request triggered action, where system will be ready to do some work when receiving a request. If it’s not asked, it shouldn’t do anything and in a while it will go to sleep.

Problem starts when you’re planning to execute some background jobs. Even if you start a background thread on application start it will go asleep along with application. When planning actions executed in pre-scheduled intervals I would strongly suggest to use an external tool, like Hangfire. For other things like listening messages you can configure your application properly.

What you need to set in IIS:

  • In Application Pool for your app, set startMode to AlwaysRunning
  • In Application Pool for your app, set idleTimeout to 0
  • In you app, set preloadEnabled to True

This of course can also be set in applicationHost.config.

You can find your applicationHost.config file in C:\Windows\System32\inetsrv\config\ directory. Then you need to edit:

	<add name="StockExample" autoStart="true" managedRuntimeVersion="v4.0" startMode="AlwaysRunning">
		<processModel idleTimeout="00:00:00" />

<site name="StockExample.Api" id="12006" serverAutoStart="true">
    <application path="/" applicationPool="StockExample">
		<virtualDirectory path="/" physicalPath="C:\sources\blog\StockExample" />
    <applicationDefaults preloadEnabled="true" />

Leave a Reply

Your email address will not be published. Required fields are marked *