Skip to content

Flush in long-running work

The package flushes when a request or a command terminates, and after each queued job. A command that runs for hours merges nothing until it ends. To merge sooner, call Metrics::flush().

app/Console/Commands/ConsumeEvents.php
use Nwidart\Metrics\Facades\Metrics;
public function handle(EventStream $stream): void
{
foreach ($stream->messages() as $message) {
$this->process($message);
Metrics::flush();
}
}

A flush merges what was recorded since the previous one. With the redis store, a flush with nothing recorded makes no call to Redis.

When units of work are small and frequent, a flush after each one costs one store call each. Flush every few seconds instead:

$lastFlush = microtime(true);
while (true) {
$this->processNext();
if (microtime(true) - $lastFlush >= 10) {
Metrics::flush();
$lastFlush = microtime(true);
}
}
  • Requests. Each one flushes after the response is sent.
  • Commands that end. Each one flushes when it terminates.
  • Queue workers and Horizon. A worker flushes after each job, including a job that fails or times out.
  • Sync jobs. They merge with the request or the command that dispatched them.

A flush never throws. If the store cannot be reached, a warning goes to the OpenTelemetry logger, the PHP error log by default, and the metrics of that flush are lost.