Queue job class with tries, backoff and timeout

Calling an LLM from a Laravel Queue Job, Safely

I use language models in a few Laravel apps now, for summaries, tagging and short replies. The part that surprised me most was not the prompt. It was everything around the call: slow responses, rate limits, and output that looks right but breaks the database. This is the setup I use.

Put the call in a queue job

Never call the model inside a web request. A slow reply holds a PHP worker, and a user who refreshes the page sends a second call. A queued job gives you retries, a timeout and a place to log failures.

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Middleware\RateLimited;

class SummariseArticle implements ShouldQueue
{
    public $tries = 4;
    public $backoff = [10, 60, 300];
    public $timeout = 45;

    public function __construct(public int $articleId) {}

    public function middleware(): array
    {
        return [new RateLimited('llm')];
    }

    public function handle(LlmClient $llm): void
    {
        $article = Article::findOrFail($this->articleId);
        $reply = $llm->summarise($article->body);
        // validate before saving, see below
    }
}
Queue job class with tries, backoff and timeout
Retries wait longer each time, so a short outage does not burn through all attempts.

Limit the rate

The RateLimited middleware holds jobs back when you go over your model provider limit, instead of failing them. The limit is a named limiter, so several jobs share it.

// app/Providers/AppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('llm', fn () => Limit::perMinute(60));

Treat the reply as untrusted input

Asking for JSON does not guarantee JSON. Sometimes you get prose, a code fence, or a field that is missing or the wrong type. Decode it, validate it like any form input, and only then save it.

$data = json_decode($reply, true);

$validator = Validator::make($data ?? [], [
    'title'   => ['required', 'string', 'max:120'],
    'summary' => ['required', 'string'],
]);

if ($validator->fails()) {
    throw new InvalidLlmReply($validator->errors()->all());
}

$article->update($validator->validated());
Code validating model output with the Validator
The validator is the contract between the model and your database.

Cost and logging

  • Store the model name, prompt version, token counts and latency for each call. Cost problems are much easier to fix when you can see them per feature.
  • Keep the raw reply when validation fails. Most of the time the prompt needs one more sentence, and the raw text shows which one.
  • Set a max token value on every call, so one long article does not cost ten times more than the rest.

What I would do differently

I would start with a smaller model and a strict validator, and only move up when the validator rejects too many replies. A cheap model with good validation is usually better than an expensive model with none.

Thanks for reading

Previous
Next
Umer
Mughal
</>
available now for work