Importing large CSV files in Laravel without running out of memory

From our own projects · Published 29 November 2026

Our first subscriber import sent the whole file to the server in one request. On a CSV of roughly 22 MB, a PHP worker ran out of memory and the browser showed “Unexpected end of JSON input”. Raising the memory limit would only have moved the failure to a larger file. We changed the design so that memory use does not depend on file size. This page describes it and shows the key parts of the controller. We do not publish timing or throughput numbers, because we have not re-measured them for this article.

The design in five steps

  1. The browser parses and maps the CSV and sends it to the server in small chunks.
  2. The server starts a transfer record and accepts chunks in order, each stored as its own small file.
  3. Chunks are checked, immutable once accepted, and safe to resend.
  4. A finalize call stitches the chunks into one spool file by streaming.
  5. A queued job reads the spool file and processes the rows. Nothing about the subscribers changes before finalize.

Hard limits that keep it bounded

public const CHUNK_BYTES = 1024 * 1024;        // 1 MiB per chunk
public const TOTAL_BYTES = 120 * 1024 * 1024;  // 120 MiB of mapped data in total
public const MAX_ROWS    = 10000000;

Each chunk must hold 1 to 500 rows and be valid JSON. The server rejects anything bigger, so the largest thing it ever holds in memory is one chunk.

Start, with an idempotent id

The client generates a UUID for the upload and sends it with the total row count. The server inserts the transfer with insertOrIgnore, then locks and re-reads the row. If the response to “start” is lost, the client can call start again with the same id and get the same transfer, not a second one. A signature of the parameters (row count, tags, options) makes a repeat call with different parameters fail with a conflict instead of silently changing the import.

Chunks: ordered, hash-checked, replay-safe

$hash = hash('sha256', $raw);
...
// Accepted chunks are immutable; lost-response replay is a no-op.
if (isset($options['chunks'][$sequence])) {
    abort_unless(hash_equals($options['chunks'][$sequence]['hash'], $hash), 409, 'An accepted chunk cannot change.');
    return $operation;
}
abort_unless($sequence === (int) $options['next_chunk'], 409, 'Upload chunks must arrive in order.');

Three rules do the work:

  • A chunk that was already accepted and arrives again with the same bytes is a no-op. That makes retries after a dropped response harmless.
  • The same sequence number with different bytes is a conflict.
  • A chunk that skips ahead is rejected, so the file is always complete up to next_chunk.

The transfer row is locked with lockForUpdate() inside a transaction, so two requests for the same transfer cannot interleave. Each accepted chunk is written to a temporary file and moved into place with rename(), which is atomic. A crash before the database commit leaves a file that a replay with the same bytes simply overwrites. The row also tracks the declared total, and the server refuses chunks that would exceed it.

Finalize: stream, do not load

foreach ($options['chunks'] as $sequence => $part) {
    $in = fopen($disk->path('uploads/'.$id.'/'.$sequence.'.jsonl'), 'rb');
    $copied = stream_copy_to_stream($in, $out);
    if ($copied !== (int) $part['bytes']) {
        throw new \RuntimeException('Upload part incomplete.');
    }
}
rename($disk->path($temp), $disk->path($path));

stream_copy_to_stream copies in buffers, so stitching a large spool file does not depend on its size. The code checks each part’s byte count against what was recorded when the chunk was accepted. Finalize refuses to run unless the uploaded row count equals the declared total.

One detail worth copying: before processing starts, the code removes the chunk manifest from the stored options. The worker saves its options as it progresses, and carrying a manifest with thousands of entries would turn every progress update into a huge database write.

Queue acceptance can be uncertain

Dispatching the job can fail in ways where you cannot tell whether the queue received it. Rather than start a second import, the code marks the transfer with a message, returns a 503, and relies on a reconciler that re-dispatches the same job. The job’s database claim is idempotent, so a duplicate dispatch does nothing harmful. The upload directory is deleted only after the dispatch is confirmed.

The controller also refuses to start at all when the queue driver is sync or null, because this design needs a worker.

Checklist

  • Bound everything: bytes per chunk, rows per chunk, total bytes, total rows.
  • Make start and chunk requests idempotent. Use a client-generated id and content hashes.
  • Lock the transfer row, and use atomic renames for files.
  • Stitch with streams. Never read the whole file into a string.
  • Change nothing in your real tables until finalize succeeds.
  • Do the heavy work in a queued job, and keep its progress writes small.

Our network