A Stack Overflow question
from a Laravel 8 → 13 upgrade has been sitting since August with one downvoted answer. Six utility
bill layouts in resources/views/bill-templates/ (electricity, gas, water, a couple with VAT, a
summary bill), barryvdh/laravel-dompdf, and a flow that saves each PDF to
storage_path('pdf_bills/<ref>.pdf'), emails it to the tenant and deletes it. The asker wants to
know whether that's the right Laravel 13 pattern, and cares about "performance, maintainability,
concurrency, and cleanup".
The short version: yes, keep Blade and a queue. Drop the file. And size the workers from what a bill actually costs, which is the part nobody has put numbers on, so here they are.
Keep the templates in the repo
Store the template key on the bill, keep the six layouts as Blade views, and check the key against an allow-list before you build a view name from it. The existing answer says this and it's right. Templates in the database buy you editing without a deploy, and cost you diffs, partials, code review and the ability to refactor a shared header in one place. For six layouts that change when the tariff rules change, that's a bad trade.
Don't write the file at all
The temp file is where both the cleanup and the concurrency problems live. Two workers, or a retry
of the same bill, write to the same pdf_bills/<ref>.pdf, and one job can delete the file the
other is about to attach. A unique name and a finally fix that. Not having a file fixes it better,
because then there's nothing to collide on and nothing to sweep.
Laravel's mailables take attachment bytes from a closure with
Attachment::fromData, and
$pdf->output() is a string. So the render moves into the mailable:
<?php
namespace App\Mail;
use App\Models\Bill;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
class BillMail extends Mailable
{
public const TEMPLATES = [
'electricity', 'electricity-with-vat', 'gas', 'water',
'multi-utility-with-vat', 'summary-bill-with-vat',
];
public function __construct(public Bill $bill) {}
public function envelope(): Envelope
{
return new Envelope(subject: "Your bill {$this->bill->hr_ref}");
}
public function content(): Content
{
return new Content(text: 'mail.bill-text');
}
public function attachments(): array
{
$template = $this->bill->template;
if (! in_array($template, self::TEMPLATES, true)) {
throw new \InvalidArgumentException("Unknown bill template [$template]");
}
return [
Attachment::fromData(fn () => Pdf::loadView("bill-templates.$template", [
'bill' => $this->bill,
'user' => $this->bill->tenant,
])->setOptions([
'dpi' => 96,
'defaultPaperSize' => 'a4',
'defaultFont' => 'Helvetica',
'isPhpEnabled' => false,
'isRemoteEnabled' => false,
])->output(), "bill-{$this->bill->hr_ref}.pdf")
->withMime('application/pdf'),
];
}
}
And the job that sends it:
<?php
namespace App\Jobs;
use App\Mail\BillMail;
use App\Models\Bill;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
class SendBill implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public int $timeout = 60;
public function __construct(public Bill $bill) {}
public function handle(): void
{
if ($this->bill->emailed_at) {
return; // a retry after the mail went out: don't send it twice
}
Mail::to($this->bill->tenant)->send(new BillMail($this->bill));
$this->bill->forceFill(['emailed_at' => now()])->save();
}
}
SendBill::dispatch($bill)->onQueue('pdfs') and you're done. The job carries only the model's id
(it's serialized as a model identifier), the PDF is built inside the worker when the message is
assembled, and it never touches disk. We ran 50 of these through queue:work with the log mail
driver: 50 messages, 50 application/pdf attachments in the log, zero .pdf files anywhere under
storage/.
Two details in the job matter more than they look. The emailed_at check means a retry after a
successful send (the worker died between the mail and the save, say) doesn't mail the tenant
twice. And $timeout = 60 stays below the queue's retry_after, which is 90 seconds in Laravel
13's default config/queue.php; the docs
explain why a timeout longer than retry_after gets jobs processed twice.
What a bill costs a worker
This is the performance half of the question. dompdf runs inside the PHP process, so for the length of a render the worker is busy and the memory is yours.
Setup: a fresh Laravel 13 app (framework v13.44.1), barryvdh/laravel-dompdf 3.1.2 on dompdf 3.1.6,
PHP 8.3.6 CLI, a 4-vCPU box, the asker's exact options, and a plain bill template: a header, a
five-column table of line items, and VAT totals. Only the number of line rows changes.
Rendering alone (fresh process per size, 9 renders, three runs):
| line rows | A4 pages | median render | PDF size | peak PHP memory |
|---|---|---|---|---|
| 10 | 1 | 24-27 ms | 2.3 KB | 36 MB |
| 40 | 2 | 83-94 ms | 4.5 KB | 40 MB |
| 200 | 5 | 524-545 ms | 16.1 KB | 68 MB |
The booted framework accounts for 20 MB of that peak before dompdf does anything. Render time
grows a little faster than linearly with rows: 5x the rows of the 40-row bill took about 6x as
long. The first render in a process is slower than the rest (71-94 ms for the 10-row bill, against
~25 ms after), which is one more reason to keep a long-lived queue:work rather than --once.
The whole job, render plus building and "sending" the mail, through queue:work:
| bill | median job | worker peak RSS |
|---|---|---|
| 10 rows | 35 ms | 80 MB |
| 40 rows | 89-90 ms | 82 MB |
| 200 rows | 521-537 ms | 114 MB |
Mail assembly adds almost nothing. The job is the render.
Draining a queue (Redis, workers started together, until the queue was empty, two runs):
| jobs | 1 worker | 2 workers | 4 workers |
|---|---|---|---|
| 200 x 40-row bills | 22.8-24.9 s | 12.9-14.1 s | 8.4-8.5 s |
| 40 x 200-row bills | 25.9-26.7 s | 8.8-9.1 s |
Two workers halve the drain time. Four on a four-core box gave about 2.8x, not 4x, so the last couple of workers buy less than the first two, and past the core count you're only adding contention. The sizing rule is still arithmetic: a 40-row bill is about a tenth of a second of one core, a summary bill with a couple of hundred lines is half a second or more. Five thousand ordinary bills at month end is roughly ten minutes on one worker, or about three and a half on four.
Memory doesn't creep. In one process, 500 renders of the 40-row bill went from 34 MB after the
first to 40 MB by the tenth and stayed there; 100 renders of the 200-row bill plateaued at
68 MB by the tenth. That's memory_get_usage(true), which is the figure the worker compares
against --memory (default 128 MB, per the
docs). So the defaults hold even for the long
summary bills; --max-jobs=1000 or --max-time=3600 under Supervisor is still a cheap safety net.
What it means for the rest of the app: put bills on their own queue, as above, with their own workers, so a month-end run of summary bills can't sit in front of password-reset mails. The existing answer says the same thing; the table is how many workers to give it.
One trap we hit in the default setup
Laravel 13's skeleton ships with SQLite and the database queue driver. With one worker that's
fine. When we started a second worker on it, we got SQLSTATE[HY000]: General error: 5 database is locked, and a job was left reserved with no worker to finish it until retry_after ran out. If
you're going to run more than one bill worker, put the queue on Redis or on your MySQL/Postgres
database first. (The numbers above are on Redis.)
When a rendering service is worth it, and when it isn't
iReceipt PRO, which publishes this blog, is a hosted rendering API. The shape is the same as above
with the render moved out of PHP: the layout is stored once as a template (HTML and CSS with
Mustache), you send the bill as JSON, and the PDF comes back as the response body. Written against
the public API reference, with template_id a new column holding the id of
the template you made for that bill type, the attachment becomes:
use Illuminate\Support\Facades\Http;
Attachment::fromData(fn () => Http::withToken(config('services.ireceipt.key'))
->timeout(30)
->post("https://api.ireceipt.pro/v1/pdf/private/{$this->bill->template_id}", [
'variables' => [
'bill' => $this->bill->only(['hr_ref', 'property', 'period', 'net', 'vat', 'total']),
'lines' => $this->bill->lines,
'tenant' => ['name' => $this->bill->tenant->name],
],
'format' => 'a4-portrait',
])
->throw()
->body(), "bill-{$this->bill->hr_ref}.pdf")
->withMime('application/pdf'),
A success is HTTP 201 with the PDF bytes. A request with no Authorization header gets 401
Unauthorized, and a key the API doesn't accept gets 403 Token invalid. So does an unset config
value, because withToken(null) still sends a bare Bearer header; if you see 403 in a fresh
environment, check the key is actually loaded. ->throw() turns any of these into an exception
the job's $tries will handle. The worker then waits on the network instead of burning a core, and the
memory table above stops applying to it. Rendered content isn't stored on our side; the
privacy policy says the API's input is "only
temporarily available during data processing".
What it costs you, and for this asker it's real:
- The six Blade views would have to be rewritten as six templates on our side. Blade
@foreachbecomes a Mustache section, and the layout leaves your repo, which is the opposite of what the first section of this article recommends. - Authoring your own templates needs a paid plan.
- The bill data goes to a third party for the length of the request.
- Our named page formats are A-series (A4 portrait is the default). For US Letter you pass a pixel
sizeof 816 x 1056 instead of aformat. - Templates can't run JavaScript or load external resources, so logos go in as base64.
If you send tens or a few hundred bills a day, none of that is worth it. dompdf in a queue with two workers will never notice. The trade starts to make sense when month-end runs are big enough that you're adding workers, and memory, only to hold renders, or when the same layouts need to come out of more than one codebase.
If you do keep dompdf and your summary bills run to several pages, the row-splitting problem is next; we wrote that one up here.