With every measurement the sensor sends a frequency spectrum (FFT), and the export spreads it into rows, one row per frequency and amplitude pair. One sensor collected about 29 thousand measurements in a year, which makes 342 thousand rows of nine columns. Over three million cells. The export from the Filament admin hit the 384 MB limit, and when I measured it, the whole process asked for 1,902 MB.
Two things were to blame, and they multiplied each other: Laravel Excel (maatwebsite/excel) and Eloquent model hydration.
Laravel Excel builds the whole workbook in memory
The original export looked roughly like this:
class MeasurementExport implements FromQuery, WithMapping, WithHeadings, WithCustomChunkSize
{
public function query(): Builder
{
return Measurement::query()
->with(['sensor.device', 'transmission.gateway'])
->whereIn('sensor_id', $this->sensorIds);
}
public function chunkSize(): int
{
return 1000;
}
}
FromQuery and chunkSize() make it look like the data is processed in batches. But only the database reads happen in batches. Every mapped row then ends up as cells in a PhpSpreadsheet Spreadsheet object, and the file is written at the very end, once the whole workbook sits in memory. One cell costs around 500 bytes. Three million cells will not fit into 384 MB.
CSV is no better. Even when you choose Excel::CSV, Laravel Excel first builds the whole Spreadsheet and only then hands it to the CSV writer.
Yet CSV needs no library at all. streamDownload() and fputcsv() into php://output are enough:
return response()->streamDownload(function () use ($rows): void {
$handle = fopen('php://output', 'w');
fputcsv($handle, self::HEADINGS, escape: '');
foreach ($rows as $row) {
fputcsv($handle, $row, escape: '');
}
fclose($handle);
}, $filename, ['Content-Type' => 'text/csv']);
For XLSX I reached for OpenSpout. It was already in the project, pulled in by filament/actions, so not a single dependency was added. OpenSpout writes row by row and keeps memory flat no matter how much data goes through:
$writer = new \OpenSpout\Writer\XLSX\Writer();
$writer->openToFile('php://output');
$writer->addRow(Row::fromValues(self::HEADINGS));
foreach ($rows as $row) {
$writer->addRow(Row::fromValues($row));
}
$writer->close();
The price for constant memory is everything Laravel Excel did through WithStyles, WithColumnFormatting and AfterSheet events. Column widths, a frozen first row, the auto filter and the header colour I wrote myself into a small class on top of OpenSpout, which all XLSX exports now share.
Hydration adds a model for every row
The second half of the problem is visible in the query() method above. Every measurement is an Eloquent model with nested relations, and on top of that a cast turns the JSON with the spectrum into a value object that holds another object for every FFT pair. A batch of a thousand measurements therefore means a thousand models, their relations and tens of thousands of small objects, of which the export needs only a few scalar values anyway.
But the export does not need a model. A database row is enough, so I replaced the relations with joins, the model with DB::table() and the cast with a plain json_decode() into an array. A generator returns the rows:
public function getIterator(): Generator
{
foreach ($this->query->lazyById(1000, 'measurements.id', 'id') as $record) {
foreach (self::fromRecord($record) as $row) {
yield $row;
}
}
}
Watch the lazyById() arguments. With a join, id in the condition is ambiguous, so I pass the column with its table and, as the third argument, the alias under which Laravel finds it in the result. Without them the query fails.
I found one more thing in the query. The year was filtered with whereYear('time', $year). For PostgreSQL, Laravel turns that into extract(year from "time") = ?, and Postgres will not use a regular index on time for an expression with a function. After switching to whereBetween() from the start to the end of the year, one batch takes 63 ms instead of 8.8 s.
Numbers
I measured on real data from the test environment. A yearly XLSX export of one sensor from the admin, including Livewire:
| Before | After | |
|---|---|---|
| Process peak memory | 1,902 MB | 166 MB |
| XLSX export duration | 40.9 s | 13.7 s |
| CSV export duration | ~10 s | 0.6 s |
The output file still has 342,460 rows and matches the original row by row.
I then rewrote the other XLSX exports the same way, with similar results. The memory of the export itself dropped from 479 MB to 9 MB, from 667 MB to under 6 MB, and the worst of them, which needed 1,467 MB and 49 s, now gets by with 5.7 MB and 25 s. Two of them only passed until now because the controller raised memory_limit to 4 GB. That can go now.