Build a Laravel Outbox Pattern for Reliable AI Events and Background Jobs

Your AI features are working locally, but in production, they are leaking money, dropping webhooks, and failing silently under load.

A user triggers an AI document analysis in your Laravel application. Your controller creates a database record, fires an HTTP request to an external LLM provider like Anthropic, OpenAI, or a self-hosted vLLM cluster, and dispatches a background job to process the result.

Then, the external AI API times out with a 504 Gateway Timeout.

Because your database transaction committed before or during the external network call, your application is now in an inconsistent state. The local record marks the task as "pending," but the LLM provider never received the request, or worse, received it, processed it, and dropped the acknowledgment webhook because your app server hiccuped for 200 milliseconds.

Developers often treat AI background jobs like standard CRUD background jobs. They throw dispatch(new ProcessAiTask($model)) inside a database transaction and hope for the best.

In modern architectures interacting with probabilistic, latency-heavy, rate-limited Large Language Models, this approach fails. You need the Transactional Outbox Pattern.


📋 Table of Contents


The Distributed Systems Fallacy in AI Applications

When building AI-powered features in Laravel, we interact with systems outside our control. Unlike a local MySQL database or an internal Redis cache, third-party AI APIs introduce latency, non-deterministic failures, variable token-per-second throughput, and strict rate limits (RPM and TPM).

[ Laravel App ] ---> ( DB Transaction: Commit Model ) ---> ❌ [ Network Partition ] ---> [ OpenAI / Anthropic ]
       |                                                                                    
       +-------> ( Dispatched Job ) ---> [ Redis Queue ] ---> ( Worker picks up job ) ---> 💥 Fails

If your code performs a database write and subsequently dispatches a queue job or triggers an API call, you have committed a dual-write. If the database commit succeeds, but the subsequent queue publication fails (e.g., Redis goes down momentarily), your user’s action is lost. Conversely, if the API call fails, your database contains a stale record with no automated recovery path.

The Transactional Outbox Pattern solves this by ensuring that database state changes and downstream messages (like AI processing triggers or webhook dispatches) are written to the same database within a single atomic transaction. A separate process then reads the outbox table and reliably delivers the messages to the queue or broker.


1. The Dual-Write Problem: Why Standard Laravel Queue Dispatches Fail

Scenario: You build an AI code-review assistant. When a user submits a pull request diff, your controller creates a CodeReview model, starts a database transaction, saves the model, and dispatches a job to call the LLM API.

Why it matters:

DB::transaction(function () {
    $review = CodeReview::create($validatedData);

    // DANGER: If Redis drops connection right here, the review is saved, 
    // but the AI job is never dispatched. The user stares at a perpetual loader.
    AnalyzeCodeWithAiJob::dispatch($review);
});

The code looks clean, and it passes unit tests where dependencies are mocked. In production under high load, Redis connection pools saturate, or network blips occur between your application server and your queue broker. The database transaction commits successfully, but dispatch() throws an exception or fails silently. Your user's request is abandoned.

Solution: Remove direct queue dispatches from transactional code paths. Instead of talking directly to Redis or SQS, write your intent directly to a dedicated outbox_events table inside the exact same database transaction as your domain model.


2. Database-Driven Outbox: Designing the Schema for High-Throughput AI Payloads

Scenario: Your AI application generates massive JSON payloads, streaming responses, multi-modal embeddings, and metadata. Storing these payloads requires a database schema designed for high throughput, fast indexing, and safe concurrent reading by multiple worker processes.

Why it matters: If your outbox table uses naive auto-incrementing integer IDs and lacks proper locking states, multiple queue workers will race to process the same AI event, resulting in duplicate LLM API calls and doubled token costs.

Solution: Create an outbox_events migration that leverages UUIDs, JSON columns for flexible payloads, and an explicit state machine tracking lifecycle transitions (pending, processing, processed, failed).

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('outbox_events', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('aggregate_type'); // e.g., 'CodeReview'
            $table->uuid('aggregate_id');     // ID of the domain model
            $table->string('event_type');     // e.g., 'code.submitted_for_ai'
            $table->json('payload');          // The serialized job data or event payload
            $table->string('status')->default('pending'); // pending, processing, processed, failed
            $table->text('error_message')->nullable();
            $table->unsignedInteger('attempts')->default(0);
            $table->timestamp('available_at')->useCurrent();
            $table->timestamps();

            // Critical indexes for relayer performance
            $table->index(['status', 'available_at']);
            $table->index(['aggregate_type', 'aggregate_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox_events');
    };
};

Why this works: By indexing status and available_at, your outbox relayer can query pending events using efficient range scans rather than full table scans. Storing payloads as JSON allows you to pass complex context windows, prompt templates, and user parameters without schema migrations every time your AI prompt structure changes.


3. Atomic Persistence: Binding Local State Changes to Outbox Events

Scenario: You need a reusable mechanism in Laravel to write domain models and outbox events simultaneously without boilerplate code cluttering your controllers or Actions.

Solution: Implement an OutboxService or repository pattern that encapsulates event recording within database transactions, paired with a clean Eloquent model helper.

namespace App\Services;

use App\Models\OutboxEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class OutboxService
{
    public function record(string $aggregateType, string $aggregateId, string $eventType, array $payload): OutboxEvent
    {
        return DB::transaction(function () use ($aggregateType, $aggregateId, $eventType, $payload) {
            return OutboxEvent::create([
                'id' => Str::uuid(),
                'aggregate_type' => $aggregateType,
                'aggregate_id' => $aggregateId,
                'event_type' => $eventType,
                'payload' => $payload,
                'status' => 'pending',
                'available_at' => now(),
            ]);
        });
    }
}

Now, inside your application controller or service action:

public function store(Request $request, OutboxService $outbox)
{
    $review = DB::transaction(function () use ($request, $outbox) {
        $review = CodeReview::create([
            'user_id' => $request->user()->id,
            'code_snippet' => $request->input('code'),
            'status' => 'queued_for_ai',
        ]);

        // Recorded atomically in the exact same transaction
        $outbox->record(
            aggregateType: CodeReview::class,
            aggregateId: $review->id,
            eventType: 'code.submitted_for_ai',
            payload: [
                'review_id' => $review->id,
                'code' => $review->code_snippet,
                'model' => 'claude-3-5-sonnet',
            ]
        );

        return $review;
    });

    return response()->json(['data' => $review, 'message' => 'Review queued successfully.'], 202);
}

💡 Practical note: If the database transaction rolls back due to a constraint violation or a thrown exception, neither the CodeReview nor the OutboxEvent will be written. Atomicity is absolute.


4. Polling vs. CDC: Choosing Your Outbox Relayer Strategy

Scenario: Your database now contains pending outbox events. How do those events get moved from your MySQL or PostgreSQL database into your Laravel queue workers (Redis/SQS)?

Why it matters: Developers often implement naive polling using a Laravel scheduled task that runs every minute:

// Naive polling in Kernel.php or Routes/Console.php
$schedule->call(function () {
    OutboxEvent::where('status', 'pending')
        ->where('available_at', '<=', now())
        ->chunkById(100, function ($events) {
            foreach ($events as $event) {
                ProcessAiOutboxJob::dispatch($event);
                $event->update(['status' => 'processing']);
            }
        });
})->everyMinute();

While simple, a 60-second polling interval is unacceptable for real-time AI code assistants or chat applications where users expect sub-second response initiation. Furthermore, running chunkById without row-level locks in high-concurrency environments leads to race conditions where multiple scheduler runs pick up the same events.

Solution: Upgrade to a high-frequency polling relayer using pessimistic locking (lockForUpdate()), or implement Change Data Capture (CDC) via Debezium if you operate at massive scale. For 95% of Laravel applications, a high-frequency database poller utilizing database-level row locking is sufficient and straightforward to maintain.

namespace App\Console\Commands;

use App\Jobs\ProcessAiOutboxJob;
use App\Models\OutboxEvent;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RelayOutboxEventsCommand extends Command
{
    protected $signature = 'outbox:relay';
    protected $description = 'Relay pending outbox events to the message queue';

    public function handle(): int
    {
        // Use pessimistic locking to prevent worker collisions
        DB::transaction(function () {
            $events = OutboxEvent::where('status', 'pending')
                ->where('available_at', '<=', now())
                ->limit(50)
                ->lockForUpdate()
                ->get();

            foreach ($events as $event) {
                // Mark as processing immediately within the lock
                $event->update(['status' => 'processing']);

                // Push to the queue
                ProcessAiOutboxJob::dispatch($event->id);
            }
        });

        return self::SUCCESS;
    }
}

Run this command via Laravel's scheduler every second using overlapping prevention:

$schedule->command('outbox:relay')->everySecond()->withoutOverlapping();

5. Handling Non-Deterministic Failures and Rate Limits

Scenario: Your outbox relayer successfully pushes the event to your queue, and your worker calls the OpenAI or Anthropic API. Suddenly, you hit an HTTP 429 Too Many Requests or an HTTP 503 Service Unavailable because the AI provider is experiencing degraded performance.

Why it matters: Standard queue retries will immediately hammer the third-party AI provider, worsening rate limits and burning through your API budget. LLM calls are expensive; failing blindly without exponential backoff and jitter is a production hazard.

Solution: Configure your Laravel queue job with intelligent backoff strategies tailored to AI provider rate-limiting headers.

namespace App\Jobs;

use App\Models\OutboxEvent;
use App\Services\AiClientService;
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 ProcessAiOutboxJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 5;
    public int $timeout = 120; // AI requests can take time

    public function __construct(public string $outboxEventId) {}

    /**
     * Calculate the number of seconds to wait before retrying the job.
     */
    public function backoff(): array
    {
        // Exponential backoff: 10s, 30s, 90s, 270s
        return [10, 30, 90, 270];
    }

    public function handle(AiClientService $aiClient): void
    {
        $event = OutboxEvent::find($this->outboxEventId);

        if (! $event || $event->status === 'processed') {
            return;
        }

        try {
            // Execute the non-deterministic AI call
            $response = $aiClient->analyze($event->payload);

            // Update domain model with AI response
            // ...

            // Mark outbox event as successfully processed
            $event->update([
                'status' => 'processed',
            ]);

        } catch (Throwable $e) {
            $event->increment('attempts');
            $event->update([
                'status' => 'pending', // Re-queue for next poll interval or retry
                'error_message' => $e->getMessage(),
                'available_at' => now()->addSeconds($this->calculateBackoff($event->attempts)),
            ]);

            throw $e; // Let Laravel queue handler log the failure
        }
    }

    protected function calculateBackoff(int $attempts): int
    {
        $backoffs = [10, 30, 90, 270, 600];
        return $backoffs[min($attempts - 1, count($backoffs) - 1)];
    }
}

⚠️ Gotcha: Never catch exceptions without re-throwing them if you rely on Laravel's built-in queue failure mechanisms and failed_jobs table. Always update your outbox event status to reflect whether it's awaiting retry or permanently dead-lettered.


6. Idempotency Keys: Surviving Duplicate Webhooks and Job Retries

Scenario: Your AI job calls an asynchronous LLM batch API or waits for a webhook callback from an asynchronous AI processing pipeline. Due to network retries, the AI provider sends the completion webhook twice for the exact same analysis.

Why it matters: If your application processes the webhook twice without idempotency guarantees, you will duplicate database records, charge the user's token balance twice, or overwrite newer state with older data.

Solution: Implement cryptographic idempotency hashing on both your outbox event creation and your inbound AI webhook handling.

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class IdempotencyService
{
    public function ensureUnique(string $key, int $ttlSeconds = 86400, callable $callback): mixed
    {
        // Use Redis atomic lock or cache add (which fails if key exists)
        $lockKey = "idempotency:{$key}";
        
        if (! Cache::add($lockKey, 'processing', $ttlSeconds)) {
            // Already processed or currently processing
            return null;
        }

        try {
            return $callback();
        } catch (\Throwable $e) {
            // Release lock on failure so it can be retried if needed
            Cache::forget($lockKey);
            throw $e;
        }
    }
}

Inside your webhook controller handling asynchronous AI completions:

use App\Services\IdempotencyService;
use Illuminate\Http\Request;

class AiWebhookController
{
    public function handle(Request $request, IdempotencyService $idempotency)
    {
        $signature = $request->header('X-AI-Provider-Signature');
        $taskId = $request->input('task_id');
        
        $idempotencyKey = hash('sha256', $taskId . $signature);

        $result = $idempotency->ensureUnique($idempotencyKey, ttlSeconds: 86400, callback: function () use ($request) {
            // Safe to process because this block executes exactly once
            $review = CodeReview::where('ai_task_id', $request->input('task_id'))->firstOrFail();
            $review->update([
                'ai_response' => $request->input('output'),
                'status' => 'completed',
            ]);

            return $review;
        });

        if (! $result) {
            return response()->json(['message' => 'Event already processed (Idempotent ignore).'], 200);
        }

        return response()->json(['message' => 'Webhook processed successfully.'], 200);
    }
}

7. Monitoring, Dead Letter Queues, and Circuit Breaking

Scenario: An external AI provider experiences a major outage lasting 4 hours. Your outbox relayer keeps picking up events, hitting timeouts, incrementing attempts, and cluttering your error tracking service with thousands of timeout exceptions.

Why it matters: Unchecked retries exhaust your queue worker capacity, block other critical background jobs (like billing or user emails), and fail to alert engineering teams until customer support tickets flood in.

Solution: Implement a Circuit Breaker pattern combined with a dedicated Dead Letter Queue (DLQ) threshold in your outbox model.

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class AiCircuitBreaker
{
    protected string $cacheKey = 'circuit_breaker:ai_provider';
    protected int $failureThreshold = 5;
    protected int $openDurationSeconds = 300; // 5 minutes

    public function isOpen(): bool
    {
        return Cache::has("{$this.cacheKey}:open");
    }

    public function recordFailure(): void
    {
        $failures = Cache::increment("{$this.cacheKey}:failures");

        if ($failures >= $this->failureThreshold) {
            Cache::put("{$this.cacheKey}:open", true, now()->addSeconds($this->openDurationSeconds));
            Log::critical("AI Provider Circuit Breaker OPENED due to repeated failures.");
        }
    }

    public function recordSuccess(): void
    {
        Cache::forget("{$this.cacheKey}:failures");
        Cache::forget("{$this.cacheKey}:open");
    }
}

Integrate the circuit breaker into your outbox relayer command:

public function handle(AiCircuitBreaker $circuitBreaker): int
{
    if ($circuitBreaker->isOpen()) {
        $this->warn('AI Circuit Breaker is OPEN. Skipping outbox relay cycle.');
        return self::SUCCESS;
    }

    // Proceed with relay logic...
}

Additionally, automatically move outbox events exceeding maximum attempts to a dead-letter state for manual inspection:

if ($event->attempts >= 5) {
    $event->update([
        'status' => 'dead_letter',
        'error_message' => 'Max attempts exceeded. Moved to DLQ.',
    ]);
    
    // Fire notification to Slack / Discord
    event(new AiOutboxMovedToDlqEvent($event));
    return;
}

Production Architecture Decision Guide

When evaluating whether your Laravel application needs the Outbox Pattern for AI workflows, use the following architectural matrix:

Architectural Dimension Direct Queue Dispatch (Standard) Transactional Outbox Pattern
Implementation Complexity Low (Job::dispatch()) Medium (New table, relayer command, state machine)
Data Consistency Weak (Vulnerable to dual-write failures) Strong (ACID guaranteed via database transactions)
AI Provider Outage Resilience Poor (Jobs fail immediately or drop on Redis failure) High (Events persist safely in DB until recovery)
Throughput & Latency Instantaneous dispatch Sub-second (Dependent on relayer poll frequency)
Cost & Token Safety High risk of duplicate API calls on retries Protected via idempotency keys and outbox states
Best Use Case Simple internal notifications, cache warmups Financial transactions, LLM calls, webhooks, billing

If your application triggers AI operations that cost real money, require audit trails, or interact with flaky external endpoints, bypassing the outbox pattern is technical debt that will eventually surface during peak traffic or provider outages.

By binding your AI events directly into your database transactions and decoupling delivery through a resilient outbox relayer, you insulate your Laravel application from external network chaos and ensure that every user prompt gets processed reliably.

Post a Comment

Previous Post Next Post