Building an AI-powered feature in a Laravel application starts as a deceptively simple task. You inject an LLM client, run a completion, return the output to your frontend, and ship it. Then your users try to generate a comprehensive 5,000-word market research report, parse an entire PDF document, or run a multi-agent coding loop.
Suddenly, your HTTP requests are timing out at 30 seconds, PHP-FPM workers are locked up, your frontend is hanging with a frozen spinner, and users are rage-clicking the submit button, spawning multiple duplicate AI jobs that burn through your API budget.
Synchronous HTTP requests are fundamentally broken for modern AI workloads. To build a robust, production-grade AI feature, you must transition to an asynchronous architecture. But simply dispatching a queued job in Laravel isn't enough. Users interacting with generative models demand high-fidelity feedback: they want live progress bars, streaming partial results, and the ability to cancel an expensive execution mid-flight.
This guide explores how to design and implement a robust Laravel API that manages AI job status, granular progress tracking, real-time partial results, and immediate cancellation.
📋 Table of Contents
- The Synchronous Trap and Why Workers Fail
- 1. Database Schema Design for Asynchronous AI Jobs
- 2. Orchestrating the Lifecycle with Laravel Queues and Batching
- 3. Capturing and Storing Granular Progress Updates
- 4. Streaming Partial Results via Server-Sent Events (SSE)
- 5. Implementing Graceful Job Cancellation and Worker Signals
- 6. Building the Client-Side State Machine and Polling Fallback
- 7. Handling Redis Connection Storms and Scaling Bottlenecks
- Production Architecture and Final Perspective
The Synchronous Trap and Why Workers Fail
When developers first integrate LLMs or generative pipelines into Laravel, they typically write something like this inside a controller:
public function generate(Request $request, OpenAIClient $ai)
{
$response = $ai->chat()->create([
'model' => 'gpt-4o',
'messages' => [['role' => 'user', 'content' => $request->input('prompt')]]
]);
return response()->json(['result' => $response->choices[0]->message->content]);
}
This approach works fine during local testing with short prompts. In production, however, it shatters under real-world conditions. OpenAI, Anthropic, or custom local models running on vLLM can take anywhere from 10 to 90 seconds to process complex payloads.
During this time:
- The PHP worker is blocked. If you have 20 concurrent users generating reports, you immediately exhaust your PHP-FPM or FrankenPHP worker pool.
- Gateway timeouts occur. Nginx or Cloudflare will ruthlessly drop the connection with a
504 Gateway Time-outafter 60 seconds, even if the AI was one token away from finishing. - Zero visibility. The user stares at a blank screen with no idea if the system is dead, processing, or hallucinating.
To solve this, we need an asynchronous processing pipeline backed by a database state machine, real-time event broadcasting, and worker-level cancellation primitives.
1. Database Schema Design for Asynchronous AI Jobs
Scenario:
You need to track AI jobs that can run for several minutes, emit partial text chunks, update a progress percentage from 0 to 100, and transition through multiple distinct states (pending, processing, completed, failed, cancelled).
Why it matters:
Laravel’s default jobs table is designed for internal queue plumbing—it lacks business context, cannot easily expose progress to a frontend API, and gets purged once a job completes. You need a dedicated Eloquent model and database table that acts as the single source of truth for the user's AI task.
Solution:
Create an ai_jobs migration and model that store metadata, raw output chunks, error messages, and cancellation tokens.
// database/migrations/2026_03_30_000000_create_ai_jobs_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::create('ai_jobs', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('job_type'); // e.g., 'market_report', 'code_refactor'
$table->string('status')->default('pending'); // pending, processing, completed, failed, cancelled
$table->unsignedTinyInteger('progress')->default(0); // 0 to 100
$table->text('current_step')->nullable(); // Human-readable status description
$table->longText('output')->nullable(); // Accumulated or final result
$table->json('metadata')->nullable(); // Input parameters, model config
$table->text('error_message')->nullable();
$table->timestamp('started_at')->nullable();
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->index(['user_id', 'status']);
});
}
public function down(): void
{
Schema::dropIfExists('ai_jobs');
}
};
Why this works:
Using UUIDs as primary keys prevents enumeration attacks where malicious actors guess sequential job IDs to view other users' sensitive AI generations. Storing output as a longText column ensures you can persist large generated payloads without hitting varchar limits, while the progress column provides an immediate integer value for frontend progress bars.
💡 Practical note: Always index columns like
user_idandstatus. When users load their dashboard, querying active AI jobs without an index will cause full table scans as your application scales.
2. Orchestrating the Lifecycle with Laravel Queues and Batching
Scenario: An AI workflow isn't always a single API call. Often, it involves a multi-step pipeline: fetching data from a database, chunking a document, sending embeddings to a vector store, invoking the LLM, and finally post-processing the output.
Why it matters: If you put all of this logic into a single monolithic queued job, debugging failures becomes a nightmare. If step 4 fails due to an external API rate limit, retrying the entire job wastes time and money by re-running steps 1 through 3.
Solution:
Use Laravel's Queue Batches or chain discrete job classes together, updating the central ai_jobs record as each phase completes.
// app/Jobs/ProcessAiTaskJob.php
namespace App\Jobs;
use App\Models\AiJob;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Throwable;
class ProcessAiTaskJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = [10, 30, 60];
public function __construct(public AiJob $aiJob) {}
public function handle(AiPipelineService $pipeline): void
{
// Check if the user cancelled before the worker even picked it up
if ($this->aiJob->fresh()->status === 'cancelled') {
return;
}
$this->aiJob->update([
'status' => 'processing',
'started_at' => now(),
'current_step' => 'Initializing AI model context...',
'progress' => 10
]);
try {
// Execute the pipeline with callbacks for progress and partial chunks
$pipeline->execute($this->aiJob, function (int $progress, string $step, ?string $chunk = null) {
// Refresh model to check for cancellation signal from user
if ($this->aiJob->fresh()->status === 'cancelled') {
throw new JobCancelledException('User requested cancellation.');
}
$updateData = [
'progress' => $progress,
'current_step' => $step,
];
if ($chunk) {
$this->aiJob->incrementOutput($chunk);
}
$this->aiJob->update($updateData);
});
$this->aiJob->update([
'status' => 'completed',
'progress' => 100,
'current_step' => 'Finished successfully.',
'completed_at' => now(),
]);
} catch (JobCancelledException $e) {
$this->aiJob->update([
'status' => 'cancelled',
'current_step' => 'Cancelled by user.',
'completed_at' => now(),
]);
} catch (Throwable $e) {
$this->aiJob->update([
'status' => 'failed',
'error_message' => $e->getMessage(),
'completed_at' => now(),
]);
throw $e; // Allow Laravel queue to handle retries if attempts remain
}
}
}
Why this works:
This job acts as an orchestrator. By injecting a callback into the AiPipelineService, we decouple the heavy lifting of talking to third-party AI APIs from the queue lifecycle management, giving us clean hooks for progress updates and error handling.
3. Capturing and Storing Granular Progress Updates
Scenario: Your AI task takes 45 seconds. If the progress bar stays at 10% for 40 seconds and then jumps straight to 100%, the user will assume the app has frozen and reload the page.
Why it matters: LLM inference isn't linear. Generating 500 tokens takes longer than generating 50 tokens. Updating database rows on every single token streamed from an LLM will utterly destroy your database performance due to write lock contention.
Solution: Implement a throttled progress buffer inside your service layer that flushes updates to the database (and optionally Redis pub/sub) at controlled intervals (e.g., every 500ms or every 10 tokens).
// app/Services/AiPipelineService.php
namespace App\Services;
use App\Models\AiJob;
use Closure;
use OpenAI\Client as OpenAIClient;
class AiPipelineService
{
public function __construct(protected OpenAIClient $openai) {}
public function execute(AiJob $aiJob, Closure $onProgress): void
{
$prompt = $aiJob->metadata['prompt'] ?? '';
// Step 1: Preprocessing & Vector search (0-30%)
$onProgress(15, 'Analyzing input context...');
$context = $this->fetchRelevantContext($prompt);
$onProgress(30, 'Preparing prompt for language model...');
// Step 2: Streaming LLM Generation (30-95%)
$stream = $this->openai->chat()->createStreamed([
'model' => 'gpt-4o',
'messages' => [
['role' => 'system', 'content' => 'You are an expert research assistant.'],
['role' => 'user', 'content' => "Context: {$context}\n\nTask: {$prompt}"]
],
]);
$accumulatedOutput = '';
$tokenCount = 0;
$lastFlushTime = microtime(true);
foreach ($stream as $response) {
$text = $response->choices[0]->delta->content ?? '';
if ($text === '') continue;
$accumulatedOutput .= $text;
$tokenCount++;
// Throttle database writes: flush every 10 tokens or 500ms
$now = microtime(true);
if ($tokenCount % 10 === 0 || ($now - $lastFlushTime) > 0.5) {
// Calculate pseudo-progress between 30% and 95 based on expected token length
$estimatedProgress = min(95, 30 + (int)($tokenCount / 2));
// Pass chunk to callback
$onProgress($estimatedProgress, 'Generating response...', $text);
$lastFlushTime = $now;
}
}
// Final completion step
$onProgress(100, 'Finalizing output...', null);
}
protected function fetchRelevantContext(string $prompt): string
{
// Stub for vector database search or RAG pipeline
usleep(500000); // Simulate network latency
return "Relevant enterprise documentation snippet...";
}
}
Why this works: By batching database writes during the high-frequency token streaming loop, we prevent database connection saturation. At the same time, we pass raw chunks downstream so clients can render text character-by-character if they are listening via Server-Sent Events or WebSockets.
4. Streaming Partial Results via Server-Sent Events (SSE)
Scenario: Your frontend needs to display the AI's response as it's being written, exactly like ChatGPT or Claude, while also keeping the progress bar accurate.
Why it matters: WebSockets (via Laravel Reverb or Pusher) are fantastic, but setting up a full WebSocket connection purely for unidirectional AI text streaming adds unnecessary client-side infrastructure complexity. For simple request-response generation loops, Server-Sent Events (SSE) over standard HTTP are simpler, work through corporate proxies more reliably, and require zero WebSocket server maintenance.
Solution:
Build a Laravel controller endpoint that returns a StreamedResponse, listening to Redis or polling the database/cache for updates emitted by the queued job.
// app/Http/Controllers/Api/AiJobStreamController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\AiJob;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class AiJobStreamController extends Controller
{
public function __invoke(Request $request, AiJob $aiJob): StreamedResponse
{
// Ensure the authenticated user owns this job
abort_unless($request->user()->id === $aiJob->user_id, 403);
return response()->stream(function () use ($aiJob) {
$lastOutputLength = strlen($aiJob->output ?? '');
$lastStatus = $aiJob->status;
$lastProgress = $aiJob->progress;
// Send initial state
echo "data: " . json_encode([
'status' => $aiJob->status,
'progress' => $aiJob->progress,
'current_step' => $aiJob->current_step,
'output' => $aiJob->output,
'error' => $aiJob->error_message,
]) . "\n\n";
ob_flush();
flush();
while (true) {
// Close connection if client aborted HTTP request
if (connection_aborted()) {
break;
}
// Refresh model state from database (or cache for high-throughput)
$aiJob->refresh();
$currentOutput = $aiJob->output ?? '';
$currentOutputLength = strlen($currentOutput);
// Check if anything changed
if (
$aiJob->status !== $lastStatus ||
$aiJob->progress !== $lastProgress ||
$currentOutputLength !== $lastOutputLength
) {
// Extract newly appended text chunk
$delta = substr($currentOutput, $lastOutputLength);
echo "data: " . json_encode([
'status' => $aiJob->status,
'progress' => $aiJob->progress,
'current_step' => $aiJob->current_step,
'delta' => $delta,
'output' => $currentOutput,
'error' => $aiJob->error_message,
]) . "\n\n";
ob_flush();
flush();
$lastOutputLength = $currentOutputLength;
$lastStatus = $aiJob->status;
$lastProgress = $aiJob->progress;
}
// Terminate stream if job reached terminal state
if (in_array($aiJob->status, ['completed', 'failed', 'cancelled'])) {
break;
}
// Sleep briefly to prevent CPU hammering on database
usleep(500000); // 500ms
}
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
'X-Accel-Buffering' => 'no', // Disable Nginx buffering for SSE
]);
}
}
Why this works:
The X-Accel-Buffering: no header is critical here. Without it, Nginx will buffer the output stream and refuse to send chunks to the browser until the entire script finishes execution, completely defeating the purpose of real-time streaming.
⚠️ Gotcha: PHP-FPM limits script execution time (
max_execution_time). For long-running SSE streams, you must callset_time_limit(0)inside the stream callback or ensure your web server and PHP-FPM pool configuration allow extended persistent connections.
5. Implementing Graceful Job Cancellation and Worker Signals
Scenario: A user kicks off a massive AI research report, realizes they typed the wrong prompt, and immediately clicks the "Cancel" button on your frontend.
Why it matters:
If your backend only updates the database status to cancelled while the background worker continues burning through expensive OpenAI API tokens for the next 2 minutes, you are wasting money and occupying queue resources unnecessarily.
Solution: Expose a dedicated cancellation API endpoint that updates the job status, and ensure the queued job periodically checks for this cancellation flag during execution.
// app/Http/Controllers/Api/AiJobCancellationController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\AiJob;
use Illuminate\Http\Request;
class AiJobCancellationController extends Controller
{
public function __invoke(Request $request, AiJob $aiJob)
{
abort_unless($request->user()->id === $aiJob->user_id, 403);
if (in_array($aiJob->status, ['completed', 'failed', 'cancelled'])) {
return response()->json([
'message' => "Job cannot be cancelled because it is already {$aiJob->status}."
], 422);
}
$aiJob->update([
'status' => 'cancelled',
'current_step' => 'Cancellation requested by user.',
'completed_at' => now(),
]);
return response()->json([
'message' => 'Job cancellation signal sent successfully.',
'job' => $aiJob
]);
}
}
Why this works:
Because our ProcessAiTaskJob repeatedly calls $this->aiJob->fresh() during the generation loop, the worker picks up the cancellation flag almost instantly. As soon as the flag is detected, the job throws a custom exception, cleanly halts execution, releases any acquired locks, and exits gracefully.
6. Building the Client-Side State Machine and Polling Fallback
Scenario: Corporate firewalls or restrictive proxy servers occasionally strip out Server-Sent Event headers, causing the SSE connection to fail silently or fall back to standard HTTP long-polling.
Why it matters: A resilient frontend cannot rely solely on WebSockets or SSE. If an SSE connection drops with a network error, your UI must handle reconnection or transparently fall back to intelligent polling without losing user-generated text.
Solution:
Construct a robust frontend utility (using modern JavaScript fetch and ReadableStream) that manages connection states, automatic retries, and fallback polling.
// resources/js/ai-job-client.js
class AiJobStreamer {
constructor(jobId, onUpdate, onError, onComplete) {
this.jobId = jobId;
this.onUpdate = onUpdate;
this.onError = onError;
this.onComplete = onComplete;
this.eventSource = null;
this.pollingTimer = null;
}
start() {
// Attempt SSE connection first
this.eventSource = new EventSource(`/api/ai-jobs/${this.jobId}/stream`);
this.eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
this.onUpdate(data);
if (['completed', 'failed', 'cancelled'].includes(data.status)) {
this.stop();
this.onComplete(data);
}
};
this.eventSource.onerror = (err) => {
console.warn('SSE connection lost. Falling back to polling...', err);
this.eventSource.close();
this.startPollingFallback();
};
}
startPollingFallback() {
this.pollingTimer = setInterval(async () => {
try {
const response = await fetch(`/api/ai-jobs/${this.jobId}`, {
headers: { 'Accept': 'application/json' }
});
if (!response.ok) throw new Error('Network response failed');
const job = await response.json();
this.onUpdate(job);
if (['completed', 'failed', 'cancelled'].includes(job.status)) {
this.stop();
this.onComplete(job);
}
} catch (error) {
this.onError(error);
this.stop();
}
}, 2000); // Poll every 2 seconds
}
stop() {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
if (this.pollingTimer) {
clearInterval(this.pollingTimer);
this.pollingTimer = null;
}
}
}
export default AiJobStreamer;
Why this works: This client-side implementation guarantees that even if a corporate proxy blocks long-lived HTTP streaming connections, your application automatically degrades gracefully to HTTP polling without breaking the user experience.
7. Handling Redis Connection Storms and Scaling Bottlenecks
Scenario: Your platform goes viral. Suddenly, 5,000 users initiate AI requests within a 30-second window. Every single browser tab opens an SSE connection, and every single background worker polls Redis or MySQL to report progress.
Why it matters: Standard relational databases will buckle under thousands of concurrent write-locks caused by high-frequency progress updates. Furthermore, open HTTP streams consume PHP-FPM worker threads, leading to thread starvation where standard API endpoints become completely unreachable.
Solution:
- Offload progress storage to Redis Cache. Instead of hitting MySQL on every token chunk, write progress and text deltas directly to Laravel's Redis cache driver, and only persist the final result to MySQL when the job completes.
- Decouple streaming from PHP-FPM. For massive scale, terminate SSE streams at a Go or Node.js gateway (or Laravel Reverb), or scale your PHP-FPM container pool independently with horizontal auto-scaling on Kubernetes.
// Optimized progress updating using Redis Cache instead of MySQL
public function updateProgress(AiJob $aiJob, int $progress, string $step, ?string $chunk = null): void
{
$cacheKey = "ai_job:{$aiJob->id}:stream";
$payload = [
'progress' => $progress,
'current_step' => $step,
'status' => 'processing',
'timestamp' => microtime(true)
];
if ($chunk) {
// Append chunk to Redis list or atomic string
\Illuminate\Support\Facades\Redis::append("ai_job:{$aiJob->id}:output", $chunk);
$payload['output'] = \Illuminate\Support\Facades\Redis::get("ai_job:{$aiJob->id}:output");
}
// Cache state for 1 hour with sub-millisecond latency
Cache::put($cacheKey, $payload, now()->hour());
}
Why this works: Redis operates entirely in memory. Shifting intermediate progress metrics and streaming chunks out of MySQL and into Redis eliminates database write contention entirely, allowing your application to handle thousands of concurrent AI generations without breaking a sweat.
Production Architecture and Final Perspective
When designing a production-grade Laravel API for AI workflows, avoid the temptation to keep things synchronous or rely on naive database polling.
Here is the architectural pattern I recommend for real-world production environments:
| Component | Technology Choice | Why |
|---|---|---|
| Queue Engine | Redis (laravel/queue) |
High throughput, supports atomic locks and pub/sub. |
| State Persistence | PostgreSQL / MySQL | Reliable ACID compliance for final job status and audit logs. |
| Intermediate State | Redis Cache | Eliminates MySQL write lock contention during token streaming. |
| Client Transport | Server-Sent Events (SSE) | Simple unidirectional streaming with automatic browser reconnection. |
| Worker Safety | Periodic Cancellation Checks | Prevents wasted API spend by stopping runaway LLM calls immediately. |
By separating job orchestration, throttling progress writes, and building graceful cancellation into your background workers, you transform a fragile wrapper around an LLM API into a resilient, enterprise-ready asynchronous processing pipeline.