#Read a large file from S3 in PHP without running out of memory
Let's say a nightly job puts all our orders into an S3 bucket: one CSV file, 16 million rows, about 1Gb.
We need the revenue per country, and our PHP process runs with the default memory_limit of 128Mb.
Doesn't look like a complicated task, right?
These scripts need a bucket, so they run only on your machine, not in the playground.
#The file
We need exports/orders.csv in a bucket named orders-exports.
The guide about uploading a large file to S3 has the script that generates the file and the one that sends it to the bucket.
#Read a file from S3 with getObject
The first answer we find is getObject from the AWS SDK for PHP.
<?php
declare(strict_types=1);
use Aws\S3\S3Client;
require __DIR__ . '/vendor/autoload.php';
$client = new S3Client(['version' => 'latest', 'region' => 'eu-west-1']);
$body = (string) $client->getObject(['Bucket' => 'orders-exports', 'Key' => 'exports/orders.csv'])['Body'];
$revenue = [];
foreach (explode("\n", trim($body)) as $number => $line) {
if ($number === 0) {
continue;
}
$row = str_getcsv($line, escape: '');
$revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3];
}
arsort($revenue);
foreach ($revenue as $country => $total) {
printf("%s %.2f\n", $country, $total);
}
GB 10030.00
FR 10010.00
DE 9990.00
US 9970.00
PL 9950.00
With a thousand rows it works. With a 100Mb file it still works, with 122Mb of memory, 6Mb below the limit. With the 1Gb file it ends like this:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1080197120 bytes)
#Why getObject runs out of memory
getObject downloads the file in one request, and (string) turns the whole answer into one string.
For our file that is 1052Mb before we read the first line, and we have 128Mb.
The script that passed every test with a small file fails on the first big export.
We could raise memory_limit, but that only moves the problem to the next, bigger file.
#Read a large file from S3 line by line
Flow reads the file in pieces and hands us one line at a time. It needs PHP 8.3 or newer. Its S3 filesystem uses AsyncAws, so the AWS SDK is not needed. The same code works with Azure Blob Storage and with an SFTP server, so every example has a tab for each of them.
S3
composer require flow-php/filesystem flow-php/filesystem-async-aws-bridge
Azure Blob Storage
composer require flow-php/filesystem flow-php/filesystem-azure-bridge nyholm/psr7
SFTP
composer require flow-php/filesystem flow-php/filesystem-sftp-bridge
And this is the whole report:
S3
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\AsyncAWS\DSL\aws_s3_filesystem;
use function Flow\Filesystem\DSL\path;
require __DIR__ . '/vendor/autoload.php';
$storage = aws_s3_filesystem('orders-exports', [
'region' => 'eu-west-1',
'accessKeyId' => $_ENV['AWS_S3_KEY'],
'accessKeySecret' => $_ENV['AWS_S3_SECRET'],
]);
$revenue = [];
foreach ($storage->readFrom(path('aws-s3://exports/orders.csv'))->readLines() as $number => $line) {
if ($number === 0) {
continue;
}
$row = str_getcsv($line, escape: '');
$revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3];
}
arsort($revenue);
foreach ($revenue as $country => $total) {
printf("%s %.2f\n", $country, $total);
}
Azure Blob Storage
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\Azure\DSL\azure_filesystem;
use function Flow\Filesystem\DSL\path;
require __DIR__ . '/vendor/autoload.php';
$storage = azure_filesystem([
'account_name' => $_ENV['AZURE_ACCOUNT'],
'container' => 'orders-exports',
'shared_key' => $_ENV['AZURE_SHARED_KEY'],
]);
$revenue = [];
foreach ($storage->readFrom(path('azure-blob://exports/orders.csv'))->readLines() as $number => $line) {
if ($number === 0) {
continue;
}
$row = str_getcsv($line, escape: '');
$revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3];
}
arsort($revenue);
foreach ($revenue as $country => $total) {
printf("%s %.2f\n", $country, $total);
}
SFTP
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\SFTP\DSL\sftp_filesystem;
use function Flow\Filesystem\DSL\path;
require __DIR__ . '/vendor/autoload.php';
$storage = sftp_filesystem([
'host' => $_ENV['SFTP_HOST'],
'user' => $_ENV['SFTP_USER'],
'password' => $_ENV['SFTP_PASSWORD'],
]);
$revenue = [];
foreach ($storage->readFrom(path('sftp://upload/exports/orders.csv'))->readLines() as $number => $line) {
if ($number === 0) {
continue;
}
$row = str_getcsv($line, escape: '');
$revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3];
}
arsort($revenue);
foreach ($revenue as $country => $total) {
printf("%s %.2f\n", $country, $total);
}
GB 10030.00
FR 10010.00
DE 9990.00
US 9970.00
PL 9950.00
That's 10Mb of memory for 16 million lines on S3, and it doesn't grow with the file.
readFrom asks S3 for the file in ranges of 9Mb, and readLines cuts every range into lines while it arrives.
#Read a part of an S3 file
Sometimes we don't need the whole file. To check that the export is complete, the last rows are enough.
$storage is the filesystem from the script above.
S3
$stream = $storage->readFrom(path('aws-s3://exports/orders.csv'));
echo $stream->read(200, $stream->size() - 200);
Azure Blob Storage
$stream = $storage->readFrom(path('azure-blob://exports/orders.csv'));
echo $stream->read(200, $stream->size() - 200);
SFTP
$stream = $storage->readFrom(path('sftp://upload/exports/orders.csv'));
echo $stream->read(200, $stream->size() - 200);
"2023-11-15 14:50:20"
998,customer998@example.com,FR,99.80,"2023-11-15 14:51:20"
999,customer999@example.com,GB,99.90,"2023-11-15 14:52:20"
1000,customer1000@example.com,PL,0.00,"2023-11-15 14:53:20"
read takes the length first, then the offset. The storage sends only these 200 bytes, the rest of the file stays where it is.
Reading 1Mb from the middle of the 1Gb file takes two requests and 0.02s.
#List files in an S3 bucket by pattern
After a few nights there is more than one export in the bucket. list takes a pattern: * matches inside one folder, ** goes through all of them.
S3
foreach ($storage->list(path('aws-s3://exports/**/*.csv')) as $file) {
echo $file->path->uri(), ' ', $file->size, "\n";
}
Azure Blob Storage
foreach ($storage->list(path('azure-blob://exports/**/*.csv')) as $file) {
echo $file->path->uri(), ' ', $file->size, "\n";
}
SFTP
foreach ($storage->list(path('sftp://upload/exports/**/*.csv')) as $file) {
echo $file->path->uri(), ' ', $file->size, "\n";
}
Every file comes back with its full path and its size:
S3
aws-s3://exports/orders-generated.csv 56721
aws-s3://exports/orders.csv 58721
Azure Blob Storage
azure-blob://exports/orders-generated.csv 56721
azure-blob://exports/orders.csv 58721
SFTP
sftp://upload/exports/orders-generated.csv 56721
sftp://upload/exports/orders.csv 58721
#Copy a file from S3 to SFTP, Azure or the disk
One day a partner wants the same export on their SFTP server, and the data team wants it in Azure.
For Flow all of them are filesystems, and file_copy moves a file between any two of them.
<?php
declare(strict_types=1);
use function Flow\Filesystem\Bridge\AsyncAWS\DSL\aws_s3_filesystem;
use function Flow\Filesystem\Bridge\Azure\DSL\azure_filesystem;
use function Flow\Filesystem\Bridge\SFTP\DSL\sftp_filesystem;
use function Flow\Filesystem\DSL\{file_copy, fstab, native_local_filesystem, path};
require __DIR__ . '/vendor/autoload.php';
$files = fstab(
native_local_filesystem(),
aws_s3_filesystem('orders-exports', [
'region' => 'eu-west-1',
'accessKeyId' => $_ENV['AWS_S3_KEY'],
'accessKeySecret' => $_ENV['AWS_S3_SECRET'],
]),
azure_filesystem([
'account_name' => $_ENV['AZURE_ACCOUNT'],
'container' => 'orders-exports',
'shared_key' => $_ENV['AZURE_SHARED_KEY'],
]),
sftp_filesystem([
'host' => $_ENV['SFTP_HOST'],
'user' => $_ENV['SFTP_USER'],
'password' => $_ENV['SFTP_PASSWORD'],
]),
);
$export = path('aws-s3://exports/orders.csv');
file_copy($files)->execute($export, path('sftp://upload/exports/orders.csv'));
file_copy($files)->execute($export, path('azure-blob://exports/orders.csv'));
file_copy($files)->execute($export, path(__DIR__ . '/orders-copy.csv'));
fstab keeps the filesystems, and the scheme of a path picks the one to use.
The file goes from S3 to the other side in pieces of 8Mb. There is no copy of it in memory.
All the options of each filesystem are in the documentation of the S3, Azure and SFTP bridges.
#How much memory does reading a file from S3 take in PHP
PHP 8.3, memory_limit=128M, a 1Gb file with 16 million rows, aws/aws-sdk-php 3.409. Each number is one run.
The S3 server runs on the same machine, so the times have no network in them.
| Task | Code | Peak memory | Time |
|---|---|---|---|
| Revenue per country | getObject as a string |
fatal error, needs 1052Mb | - |
| Revenue per country | Flow readLines |
10Mb | 3.5s |
| 1Mb from the middle | Flow read |
10Mb | 0.02s |
| Copy to the disk | Flow file_copy |
32Mb | 2.7s |
The numbers that matter are the ones that don't change. With a 100Mb file readLines takes 12Mb.
Only getObject grows with the file: 122Mb for 100Mb, 1052Mb for 1Gb.
To check it on your machine, add this line at the end of any of the scripts above:
printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024);