Jobs tuning

Published

Updated

🎛️

All jobs of a fortrabbit environment share the memory of the Jobs component and restart on every deployment. Handle the exit signal, keep processes attached, and spread cron schedules.

Memory

All jobs of an environment share the memory of the Jobs component. Keep the peak of all jobs together below that limit; the jobs memory metric shows it. A job that runs out of memory is killed, see out of memory.

A worker that exits often points to an error. Check the jobs logs.

Graceful shutdown

Every deployment and every change to a job restarts it. The job first gets the exit signal, SIGTERM by default, and SIGKILL once the exit timeout has passed. To finish the current task before stopping, handle the signal with the PCNTL extension, which is always on.

The simplest PHP script for a job is a while loop:

while (true) {
  do_something();
  sleep(5);
}
php

To make sure do_something() is never cut off, extend it like this:

declare(ticks=1);

$shutdown = false;
pcntl_signal(SIGTERM, function($signo) use (&$shutdown) {
    error_log("Received shutdown signal");
    $shutdown = true;
});

while (true) {
  do_something();
  foreach (range(1, 5) as $num) {
    if ($shutdown) {
      error_log("Shutting down safely");
      exit(0);
    }
    sleep(1);
  }
}
php

Do not detach

A job must stay attached to the process that started it, so the platform can monitor it. Processes that detach from it are killed.

Overlapping jobs

A cron that runs longer than its interval starts again while the last run is still going. Set a max runtime shorter than the interval, or make the command skip a run while another one is active. The platform limits how many instances of the same job run in parallel.

Memory peaks in the jobs metrics at the same minute every hour or day often mean several crons start together. Spread the schedules: every process needs its own memory.

Written by humans and AI in collaboration.

AI use & editorial processEdit on GitHub ↗