A two-year overview page on a large customer died at 1 GB with Clockwork switched on. With Clockwork off, the same request completed, at about 1 GB.

That page is heavy either way, and I’m not pretending otherwise. But a profiler’s whole job is to show you what a request is doing, and this one was killing the exact request I wanted to look at. Production was never affected, because Clockwork only runs with CLOCKWORK_ENABLE=true. We use Clockwork to analyze N+1 queries, and the largest pages are where those hurt most, so the biggest requests were exactly the ones I could no longer see.

I wasn’t looking for this bug. I found it while debugging something else.

Where the memory went

A year ago I wrote about a helper called addClockworkEvent(), and said the afternoon spent on that instrumentation was the work I’d recommend most. I still think so. But I had also wired it into the template handler, so every template render reported itself:

addClockworkEvent($this->getFilename(), $exposed);

$exposed is everything the template can see, which can be every model on the page. And a template that renders one row runs once per row.

Inside the helper, the parameters went through this:

clock()->addEvent(
    $eventName,
    json_decode(json_encode($eventParameters)),
    // ...
);

So each row of the page took a full copy of all the page’s data and stored it in an event that lives until the end of the request. Memory grew with rows times data, and the pages with the most rows are also the ones with the most data.

The line was mine

The first version of the helper, in October last year, passed (object)$eventParameters. A week later I replaced it with the JSON round trip, in a commit whose title calls it a “safer” conversion, marked as a hotfix.

The commit doesn’t record what broke. Whatever it fixed, the cost on big pages went unnoticed, and the line sat there for a year.

Why a round trip is so much worse than it looks

What makes this line expensive is specific to PHP. Arrays are copy-on-write, so holding on to the same array in 500 places costs almost nothing until someone writes to it. A JSON round trip throws that away, because every call builds a brand new structure.

I measured it with a synthetic 2,000-row array, stored 500 times:

What each event keepsMemory for 500 events
The array itself0.0 MB
json_decode(json_encode(…))628.5 MB
A summary like array(2000)0.21 MB

The numbers are from a toy script, so don’t read them as the size of the real page. The shape is the point: the line looks like a harmless type conversion, and it turns a free reference into a deep copy.

The fix

An event in a timeline doesn’t need the data. It needs enough to tell you what was there. So template events now record a summary:

return array_map(static function ($value) {
    if (is_array($value)) {
        return 'array(' . count($value) . ')';
    }
    if (is_object($value)) {
        return $value::class;
    }

    return is_string($value) ? mb_strimwidth($value, 0, 120, '…') : $value;
}, $parameters);

Stack traces had the same problem at a smaller scale. Every query stored its full trace, and most of it was lifecycle boilerplate repeated for each query. The nearest frames identify the caller, so traces now keep eight:

$filtered = array_slice(array_values($filtered), 0, 8);

On a one-week overview, the log went from 14.9 MB to 5.5 MB, and peak memory went from 88 MB to 44 MB. I also stopped logging static assets, which are served through PHP here and were burying the real requests.

Two settings nothing was reading

While I was in the setup code, I found two options that were doing nothing. We passed Clockwork a storage object:

'storage' => new Clockwork\Storage\FileStorage(PATH_SERVER_BASE . 'cache/clockwork'),
'trace' => true,

Clockwork’s storage option is a string. Its makeStorage() checks for sql and redis, and anything else gets a default FileStorage, so our object and our path were silently replaced. trace isn’t a key in its config at all. Both looked like decisions, and neither was one.

The same setup hid a trap for the fix. init() merges config with a plain array_merge, so a nested block has to arrive complete. Passing only the except list inside requests would drop the other keys and fatal at shutdown, so it starts from Clockwork’s own defaults:

'requests' => array_replace($clockworkDefaults['requests'], [
    'except' => ['^/admin/static/', '^/favicon\.ico'],
]),

The request you most want to see

Shrinking the log wasn’t quite enough. Clockwork writes its log in a shutdown function, and shutdown functions do run after an out-of-memory fatal. But they run under the same limit that just killed the request, so writing the log can fail at the moment it matters most. A small test confirmed it: after exhausting a 32 MB limit, the shutdown function ran, and its next large allocation died with the same fatal error.

So the shutdown handler now gives itself room first:

register_shutdown_function(function () use ($clockwork) {
    ini_set('memory_limit', (string) (memory_get_usage(true) + 512 * 1024 * 1024));
    $clockwork->requestProcessed();
});

The same test with that line added allocated fine. It’s a fixed 512 MB rather than -1 on purpose, so a runaway log can’t exhaust the whole container and take MySQL down with it. The request’s own peak has already been recorded by then, so the extra headroom doesn’t distort the numbers.

The takeaway

Instrumentation has a cost, and that cost scales with what it observes. Mine was survivable on smaller pages and fatal on the largest ones, which are the pages you reach for a profiler to understand. So measure the tool on your worst request, not on a typical one.

Two smaller things stuck with me. When a debugging tool stores what it sees, the question to ask is what it needs to keep, because “everything, just in case” is how a timeline event ends up holding a page’s data. And a debug tool has to survive the failure it exists to explain. If the requests that crash are the ones that vanish from the log, it works everywhere except where you need it.

The line that caused all this was mine, and I’d called it safer in the commit title. Maybe it was, for whatever it fixed that day. A hotfix only answers the question you asked when you wrote it.