Most early-stage Laravel SaaS codebases don't stall because Laravel hit a ceiling. They stall around 5,000 active users because three core foundations — tenant isolation, composite index ordering, and idempotent billing — were deferred as "Phase 2" polish while the team rushed to ship screens.
Everything feels instant on 200 seed rows in local dev. Then real concurrent tenants arrive: unindexed WHERE workspace_id = ? ORDER BY created_at DESC queries trigger filesorts, overlapping Stripe webhook retries double-credit accounts, and a single missing tenant check turns into a painful security audit.
Note: If you're sharing the business case, sprint timeline, or build-model comparison with a non-technical co-founder or stakeholder, I published the executive companion playbook here: Shipping a Production SaaS MVP in 2–4 Weeks Without a £50k Rewrite.
This guide covers the exact Laravel 13, PHP 8.4, MySQL 8, Redis, and Pest 5 implementation patterns I lock in during Week 1 so an MVP can grow smoothly without a rewrite.
01. Cardinality-Ordered Composite Indexes from Migration #1
Single-column foreign keys ($table->foreignId('workspace_id')->constrained()) look tidy in a migration, then fall apart the moment a busy workspace accumulates 50,000+ rows and your dashboard filters by status and sorts by created_at DESC.
MySQL can typically only use one B-Tree index efficiently per table reference. If workspace_id and created_at live in separate single-column indexes, EXPLAIN ANALYZE quickly reveals Using filesort and Using temporary — eating CPU under burst concurrency.
Instead, align a cardinality-ordered composite index directly to your hot query path (equality columns first → sort/tie-breaker columns last):
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('workspace_activities', function (Blueprint $table): void {
$table->id();
$table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->string('status', 32)->default('active');
$table->string('event_type', 64);
$table->json('payload')->nullable();
$table->timestamps();
});
// MySQL 8 supports true DESC key parts to avoid backward index scans
// on high-concurrency "latest first" feeds:
if (DB::getDriverName() === 'mysql') {
DB::statement(
'ALTER TABLE workspace_activities
ADD INDEX idx_activities_workspace_status_created (
workspace_id,
status,
created_at DESC,
id DESC
)'
);
} else {
Schema::table('workspace_activities', function (Blueprint $table): void {
$table->index(
['workspace_id', 'status', 'created_at', 'id'],
'idx_activities_workspace_status_created'
);
});
}
}
public function down(): void
{
Schema::dropIfExists('workspace_activities');
}
};
Now your dashboard feed query resolves in a single ordered B-Tree range scan with zero filesorts:
$activities = WorkspaceActivity::query()
->where('workspace_id', $workspace->id)
->where('status', 'active')
->orderByDesc('created_at')
->orderByDesc('id')
->limit(25)
->get(['id', 'user_id', 'event_type', 'created_at']);
I go deeper into EXPLAIN ANALYZE, sticky read/write replica splitting, and singleflight Redis cache locks in my High-Availability 1 Million DAU Laravel & MySQL Case Study.
02. Multi-Tenant Isolation Without Leaky Global Scopes
A classic Laravel multi-tenancy trap is relying solely on an Eloquent Global Scope that calls auth()->user()->workspace_id.
Why it breaks in production:
- Inside queued jobs, webhooks, and scheduled Artisan commands,
auth()->user()isnull— either throwing silently or querying across all workspaces if the scope guards withif (auth()->check()). - Route model binding (
/projects/{project}) can resolve another tenant's record before a developer remembers to check ownership inside a controller.
A cleaner, auditable Day-1 pattern pairs explicit query scopes, strict policies, and explicit workspaceId serialization on every queued job:
<?php
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Builder;
trait BelongsToWorkspace
{
/**
* Scope queries strictly to a single workspace boundary.
*
* @param Builder<static> $query
* @return Builder<static>
*/
public function scopeForWorkspace(Builder $query, int $workspaceId): Builder
{
return $query->where($this->qualifyColumn('workspace_id'), $workspaceId);
}
}
Pair that with a dedicated policy so every route and Livewire action enforces the exact same rule:
<?php
namespace App\Policies;
use App\Models\Project;
use App\Models\User;
class ProjectPolicy
{
public function view(User $user, Project $project): bool
{
return $user->workspace_id === $project->workspace_id;
}
public function update(User $user, Project $project): bool
{
return $user->workspace_id === $project->workspace_id
&& $user->hasWorkspaceRole(['owner', 'admin']);
}
}
And inside asynchronous jobs, pass the scalar workspaceId explicitly instead of assuming ambient request/session state:
<?php
namespace App\Jobs;
use App\Models\Project;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class GenerateWorkspaceReport implements ShouldQueue
{
use Queueable;
public function __construct(
public int $workspaceId,
public int $projectId,
) {}
public function handle(): void
{
$project = Project::query()
->forWorkspace($this->workspaceId)
->findOrFail($this->projectId);
// Process report strictly inside $this->workspaceId
}
}
Zero hidden magic, zero auth() assumptions inside queue workers, and trivial to trace during security reviews.
03. Idempotent Stripe Webhooks with Redis Locks + DB Unique Constraints
In production, Stripe webhooks will eventually arrive out of order, time out mid-flight, and retry aggressively — sometimes hitting two PHP-FPM workers in the exact same millisecond.
A naive controller running $workspace->increment('credits', 1000) on invoice.paid is guaranteed to double-credit someone.
Treat every inbound billing event as an idempotent state transition protected at two layers:
-
Distributed Redis lock (
Cache::lock) to serialize concurrent deliveries for the same event/workspace. -
Database
UNIQUE (stripe_event_id)constraint +lockForUpdate()insideDB::transaction()as an unbreakable persistence guardrail.
First, create a lightweight receipt table for processed webhook events:
Schema::create('processed_stripe_events', function (Blueprint $table): void {
$table->id();
$table->string('stripe_event_id')->unique();
$table->string('event_type', 100);
$table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
$table->timestamp('processed_at');
});
Then route webhook processing through a single-purpose idempotent settlement Action:
<?php
namespace App\Actions\Billing;
use App\Enums\SubscriptionStatus;
use App\Models\ProcessedStripeEvent;
use App\Models\Workspace;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class SettleStripeInvoiceAction
{
public function execute(
string $stripeEventId,
int $workspaceId,
string $planCode,
int $creditGrant = 0,
): bool {
return (bool) Cache::lock("stripe:event:{$stripeEventId}", 10)
->block(5, function () use ($stripeEventId, $workspaceId, $planCode, $creditGrant): bool {
try {
return DB::transaction(function () use ($stripeEventId, $workspaceId, $planCode, $creditGrant): bool {
if (ProcessedStripeEvent::query()->where('stripe_event_id', $stripeEventId)->exists()) {
return false; // Safe idempotent no-op on retry
}
$workspace = Workspace::query()
->lockForUpdate()
->findOrFail($workspaceId);
// Unique index on stripe_event_id acts as the final DB safety net
ProcessedStripeEvent::query()->create([
'stripe_event_id' => $stripeEventId,
'event_type' => 'invoice.paid',
'workspace_id' => $workspace->id,
'processed_at' => now(),
]);
$workspace->update([
'plan_code' => $planCode,
'subscription_status' => SubscriptionStatus::Active,
'credit_balance' => $workspace->credit_balance + $creditGrant,
]);
return true;
});
} catch (UniqueConstraintViolationException) {
return false;
}
});
}
}
When a duplicate retry arrives, SettleStripeInvoiceAction::execute() returns false, your webhook endpoint still responds 200 OK (telling Stripe to stop retrying), and the workspace balance is never mutated twice.
If your roadmap includes multi-currency or non-custodial rails alongside cards, you can see the full double-entry ledger and state-machine architecture in my Dual-Rail Fiat & Crypto Payment Gateway Case Study.
04. Why One Unified Laravel 13 + Livewire 4 Stack Beats Premature Split Repos
Before product-market fit, splitting a lean SaaS into a separate React/Next.js SPA repo and a separate Laravel API repo introduces massive hidden tax:
- Duplicated validation rules and TypeScript DTO definitions
- Auth cookie/CORS/CSRF sync edge cases across subdomains
- Two CI pipelines, two deployments, and twice the context-switching on every small UI iteration
With Laravel 13, PHP 8.4, Livewire 4, Alpine.js, and Tailwind CSS v4, your server-rendered components hold strict PHP validation, authorization policies, and Eloquent queries in one cohesive repository — while still streaming real-time UI updates and offloading heavy work (or LLM calls) onto Redis queues.
Cutting product surface area down to one core paid workflow while keeping a unified, well-indexed backend is how teams ship in 2–4 weeks without creating a 5,000-user rewrite cliff.
05. The 3 Pest 5 Feature Tests That Pass Technical Due Diligence on Day 1
When Seed/Series A technical diligence or enterprise security teams review an early repo, they don't expect 100% line coverage on marketing pages. They immediately look for automated tests proving tenant isolation and payment integrity.
Adding these three Pest 5 tests in Week 1 takes 20 minutes and catches the highest-severity regressions before production:
<?php
use App\Actions\Billing\SettleStripeInvoiceAction;
use App\Models\Project;
use App\Models\User;
use App\Models\Workspace;
test('users cannot view or update records belonging to another workspace', function () {
$workspaceA = Workspace::factory()->create();
$workspaceB = Workspace::factory()->create();
$userA = User::factory()->for($workspaceA)->create();
$projectB = Project::factory()->for($workspaceB)->create();
$this->actingAs($userA)
->get(route('projects.show', $projectB))
->assertForbidden();
$this->actingAs($userA)
->patch(route('projects.update', $projectB), ['name' => 'Hijacked'])
->assertForbidden();
expect($projectB->fresh()->name)->not->toBe('Hijacked');
});
test('replaying the same stripe invoice.paid event credits the workspace strictly once', function () {
$workspace = Workspace::factory()->create([
'credit_balance' => 0,
]);
$action = app(SettleStripeInvoiceAction::class);
$firstRun = $action->execute(
stripeEventId: 'evt_test_idempotent_001',
workspaceId: $workspace->id,
planCode: 'pro_monthly',
creditGrant: 1000,
);
$duplicateRetry = $action->execute(
stripeEventId: 'evt_test_idempotent_001',
workspaceId: $workspace->id,
planCode: 'pro_monthly',
creditGrant: 1000,
);
expect($firstRun)->toBeTrue()
->and($duplicateRetry)->toBeFalse()
->and($workspace->fresh()->credit_balance)->toBe(1000);
});
test('stripe webhook endpoint rejects requests with an invalid signature before mutating state', function () {
$payload = json_encode([
'id' => 'evt_invalid_sig_001',
'type' => 'invoice.paid',
], JSON_THROW_ON_ERROR);
$this->withHeaders([
'Stripe-Signature' => 't=1700000000,v1=invalid_hmac_signature',
])
->postJson('/webhooks/stripe', json_decode($payload, true))
->assertStatus(400);
$this->assertDatabaseMissing('processed_stripe_events', [
'stripe_event_id' => 'evt_invalid_sig_001',
]);
});
Wrapping Up & Live Proof
None of these patterns slow down an early sprint — together, the composite index migration, explicit tenant scoping, Redis + DB idempotency guard, and 3 Pest tests take a single afternoon on Day 1, and routinely save months of production firefighting later.
If you want to inspect more of this stack in action:
- Founder & Executive Playbook (2–4 Week Sprint Blueprint): boswell.dev/articles/saas-mvp-architecture-2-4-weeks-without-rewrite
- Live Laravel 13 + Livewire 4 AI Sandbox (No Signup): boswell.dev/ai-demo — 5 bounded workflows backed by deterministic PHP validation
- Architecture Audits & SaaS MVP Sprints: boswell.dev/founders
What Day-1 Laravel or MySQL safeguard has saved your team the biggest headache in production? Drop it in the comments — always keen to compare notes.

Top comments (8)
Leading every MySQL 8 composite index with
tenant_idkeeps InnoDB B-tree range scans tight and buffer pool pages warm, though Redis-locked Stripe webhooks still need a durable database idempotency key so a lock TTL expiry or Redis failover never double-provisions a tenant. Locks expire, ledgers don't.Thanks Kürşat! "Locks expire, ledgers don't" is the perfect way to phrase it.
You're completely right. Leading with tenant_id keeps those buffer pools happy, and while Redis is a great first line of defence for serializing webhook traffic, the database unique constraint is the ultimate, unbreakable safety net.
Solid Week-1 list. Two webhook details - the first from our shipped billing code, the second a general practice we recommend:
The processed-events guard keys on the Stripe event id, which handles retries of the same event. The trickier duplicate is two different events describing one business transition: invoice.paid and customer.subscription.updated can both land for the same renewal, sometimes out of order. If grant logic lives in both handlers, the event-id check won't catch it. We key the credit grant on the provider's invoice/transaction reference as well, and order applied events by the provider's timestamps rather than arrival order.
Second, as general practice: consider having the endpoint do nothing but verify the signature, persist the raw event, and dispatch a job. Stripe's request timeout is unforgiving, and a slow settlement (DB transaction plus lock wait) will burn it on a busy day. A queue retry is friendlier than a Stripe retry because you control the backoff.
Spot on, Keel! Thanks so much for sharing these, they're hard won lessons that only surface after real production battle scars.
Invoice ID for ledgers: You're completely right. Stripe's event overlap is a classic trap, and tying the ledger mutation directly to the invoice_id is the true safeguard.
Async Webhook Dispatch: I love this point. Sync gets the MVP out the door, but validating the HMAC and immediately kicking the payload to a Redis queue is definitely the gold standard to beat Stripe's unforgiving timeouts.
Really appreciate you adding this, excellent advice!
Thanks Warren, glad it was useful. One accuracy note on my own comment, which I've now edited: the invoice-reference keying and timestamp ordering are in our shipped, regression-tested code; the queue-dispatch point is general practice rather than what we run today - our handler processes inline after signature verification, with the durable receipt doing the heavy lifting. Your Redis lock plus database constraint combo covers the same ground either way.
Glad it landed, Warren. Keying the ledger mutation to invoice_id removes a real failure class: Stripe's retries and overlapping events can otherwise apply the same payment twice. Good luck with the build.
Explicit workspaceId on queued jobs. A global scope leaning on auth()->user() stays quiet until a webhook runs with no user at all.
Great point, Odinaka! That's exactly it.
Relying on auth()->user() in a global scope is a ticking time bomb the second you introduce webhooks or background queues. Passing the workspaceId explicitly removes that headache completely.
Thanks so much for reading and commenting