php 49 lines · 7 steps

Serializing balance reconciliation in Laravel

A queued Laravel job that reconciles an account against Stripe while preventing concurrent runs for the same account.

Explained by highlit
1<?php
2 
3namespace App\Jobs;
4 
5use App\Models\Account;
6use App\Services\StripeReconciler;
7use Illuminate\Bus\Queueable;
8use Illuminate\Contracts\Queue\ShouldQueue;
9use Illuminate\Foundation\Bus\Dispatchable;
10use Illuminate\Queue\InteractsWithQueue;
11use Illuminate\Queue\Middleware\WithoutOverlapping;
12use Illuminate\Queue\SerializesModels;
13 
14class ReconcileAccountBalance implements ShouldQueue
15{
16 use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
17 
18 public int $tries = 3;
19 
20 public function __construct(public Account $account)
21 {
22 }
23 
24 public function middleware(): array
25 {
26 return [
27 (new WithoutOverlapping($this->account->id))
28 ->expireAfter(180)
29 ->releaseAfter(30)
30 ->dontRelease(),
31 ];
32 }
33 
34 public function handle(StripeReconciler $reconciler): void
35 {
36 $ledger = $reconciler->pullLedger($this->account);
37 
38 $this->account->forceFill([
39 'balance_cents' => $ledger->settledCents(),
40 'pending_cents' => $ledger->pendingCents(),
41 'reconciled_at' => now(),
42 ])->save();
43 }
44 
45 public function uniqueId(): string
46 {
47 return (string) $this->account->id;
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1WithoutOverlapping keyed by a stable id keeps mutually-destructive jobs from running at the same time.
  2. 2Pairing expireAfter with dontRelease avoids permanent locks while discarding redundant work instead of retrying it.
  3. 3Injecting a service into handle keeps the job thin and lets the queue container resolve dependencies for you.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serializing balance reconciliation in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code