Why do modules run multiple times on a single page load? In Drupal 7 created a module which implemented hook_init().

I put an error log message as the first line of the function.

function my_module_init() {
  error_log('running init');
}


On each page load of the site I see the error message multiple times. I was expecting hook_init() to be ran exactly once per page load. Why is it running multiple times?
hook_init() is invoked by Drupal only once for each requested page; it is the last step done in _drupal_bootstrap_full().

  // Drupal 6
  //
  // Let all modules take action before menu system handles the request
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    module_invoke_all('init');
  }




  // Drupal 7
  //
  // Let all modules take action before the menu system handles the request.
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
    // one for this page), so that:
    // - Modules with hook_init() implementations that call theme() or
//   theme_get_registry() don't initialize the incorrect theme.
    // - The theme can have hook_*_alter() implementations affect page building
//   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
//   ahead of when rendering starts.
    menu_set_custom_theme();
    drupal_theme_initialize();
    module_invoke_all('init');
  }


If hook_init() is being executed more than once per each page request, there could be a module that calls module_invoke_all('init'). It could also happens that a module calls drupal_goto(), and redirects the user to another page; this would cause a new page request, and a new invocation of hook_init(), if the page is not served from the cache.

In Drupal 7, there is just a way to check if hook_init() is invoked twice per page request, and it is to implement hook_init() using the following code.

function mymodule_init() {
  watchdog('mymodule', 'Request time: !timestamp', array('!timestamp' =&gt; REQUEST_TIME), WATCHDOG_DEBUG);
}


As REQUEST_TIME is a constant that Drupal defines each times it bootstraps (which means each times a page is requested), if you see two consecutive watchdog() entries showing the same value, then hook_init() is being invoked twice, or it is invoked in two different page requests done in less than a second. If the difference is 2 seconds, for example, then hook_init() is invoked in two different page requests.