Pattern Playbook

Course › Day 7 · Production › Scene 41 of 49 · 30 min

iCal calendars are three hours out of date

Changes worked out in memory and written in one short transaction: upsert(), one delete, only real differences written; follow-up: deadlocks, REPEATABLE READ, gap and next-key locks

Unit of Work

On this page
  1. The incident
  2. The broken code
  3. The fix, part 1: work out every change first, then write them together
  4. The fix, part 2: one queued sync per feed, and no push when nothing changed
  5. The pattern
  6. Laravel inside: what upsert() sends to MySQL
  7. Tests
  8. Follow-up, the same afternoon: deadlocks between two feeds of one cottage
  9. The broken code
  10. What REPEATABLE READ locks: rows and the gaps between them
  11. The fix: one sync per property at a time, and a retry for the rare deadlock left
  12. Remember

#opsWednesday 11:05

Karim · developerHorizon: 9,400 SyncIcalFeed jobs waiting on the default queue. The oldest was queued three hours ago, and guest emails are waiting behind them.

Mona · supportTwo overbookings this morning, both at Hygge Homes cottages: Airbnb sold the nights at 08:12, and our site sold them again at 09:30. Their Airbnb feed hadn’t been read since 07:50.

Sara · tech leadHygge’s 280 feeds were switched on at 07:45 this morning. We now have 3,100 feeds, each synced every 15 minutes, and the workers can’t keep up.

The broken code

Scene 12’s importer saves every event of the feed, one by one, every time:

app/Channels/Ical/IcalImporter.php (the save step, before)the bug
DB::transaction(function () use ($feed, $events): void {
    foreach ($events as $event) {                                       // the bug: 400 events = 400 selects + up to 400 writes
        ExternalBlock::updateOrCreate(
            ['property_id' => $feed->property_id, 'source' => $feed->source, 'uid' => $event->uid],
            ['kind' => $event->kind, 'starts_on' => $event->stay->checkIn->toDateString(), 'ends_on' => $event->stay->checkOut->toDateString()],
        );
    }
    // … delete what is gone, update last_synced_at …
});

On Day 3 a feed had 20 events and this took milliseconds. A Booking.com feed of a busy cottage lists every closed night of the coming year: about 400 events, and an agency’s cottage that is booked solid has over a thousand. Each updateOrCreate() is a SELECT and, if anything differs, an UPDATE; almost always nothing differs, because the calendar didn’t change in 15 minutes. So a sync downloads the feed and then runs a query or two per event to learn that nothing changed: about 1.2 seconds of a worker’s time for an average feed, 4.5 for one of Hygge’s.

The arithmetic: until yesterday, 2,820 feeds × 1.2 s ≈ 56 minutes of work every 15 minutes, for 4 workers that have 60. Nobody was watching that margin. Hygge’s 280 feeds add 21 minutes: 78 minutes of work for 60, an average of 1.5 s a feed. Every 15 minutes the scheduler queues all 3,100 again, so about 700 jobs more arrive than leave, and many are the same feed queued two or three times.

How the fix works, in one picture

Before

every eventupdateOrCreate3,100 feeds: queue grows

Each sync wrote row by row, whether anything changed or not.

After

diff in memory1 upsert + 1 deleteonly changesmost syncs write nothing

Changes are worked out in memory and written once: one upsert, one delete.

The fix, part 1: work out every change first, then write them together

The feed’s current blocks are loaded once. Each event in the new feed is compared in memory: unknown UID → new; known UID with other dates or kind → changed; identical → nothing. Blocks whose UID isn’t in the feed any more are removed. Only then does anything touch the database, in one short transaction: one upsert() for new and changed rows, one delete() for removed ones.

A feed that didn’t change, which is nearly all of them, costs one SELECT and no writes to external_blocks at all.

app/Channels/Ical/BlockChanges.phpnew file
<?php

namespace App\Channels\Ical;

use App\Models\ExternalBlock;
use App\Models\IcalFeed;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

/** Everything one sync changes in a feed's blocks, collected first and written in one go. */
final class BlockChanges
{
    /** @var list<array<string, string|int>> rows to insert or update */
    private array $upserts = [];

    /** @var array<string, true> the UIDs the feed still contains */
    private array $seen = [];

    /** @param Collection<string, ExternalBlock> $current the feed's blocks now, by UID */
    private function __construct(
        private readonly IcalFeed $feed,
        private readonly Collection $current,
    ) {
    }

    public static function for(IcalFeed $feed): self
    {
        $current = ExternalBlock::query()
            ->where('property_id', $feed->property_id)
            ->where('source', $feed->source)                            // only this channel's blocks (scene 12)
            ->get()
            ->keyBy('uid');                                             // one query for the whole feed

        return new self($feed, $current);
    }

    /** Register one event of the new feed: new, changed or the same. Nothing is written yet. */
    public function seen(IcalEvent $event): void
    {
        $this->seen[$event->uid] = true;
        $block = $this->current->get($event->uid);

        $startsOn = $event->stay->checkIn->toDateString();
        $endsOn = $event->stay->checkOut->toDateString();

        if ($block !== null && $block->kind === $event->kind
            && $block->starts_on->toDateString() === $startsOn && $block->ends_on->toDateString() === $endsOn) {
            return;                                                     // identical: nothing to write
        }

        $this->upserts[] = [
            'property_id' => $this->feed->property_id,
            'source' => $this->feed->source->value,                     // raw rows: the enum's value, not the enum
            'uid' => $event->uid,
            'kind' => $event->kind,
            'starts_on' => $startsOn,
            'ends_on' => $endsOn,
        ];
    }

    /** Write every registered change in one short transaction. @return int the number of rows inserted, updated or deleted */
    public function commit(): int
    {
        $removedIds = $this->current
            ->reject(fn (ExternalBlock $block): bool => isset($this->seen[$block->uid]))
            ->pluck('id')
            ->all();

        if ($this->upserts === [] && $removedIds === []) {
            return 0;                                                   // the usual case: no transaction at all
        }

        DB::transaction(function () use ($removedIds): void {
            foreach (array_chunk($this->upserts, 500) as $rows) {       // a year of new blocks: still a few statements
                ExternalBlock::upsert($rows, uniqueBy: ['property_id', 'source', 'uid'], update: ['kind', 'starts_on', 'ends_on']);
            }

            if ($removedIds !== []) {
                ExternalBlock::whereKey($removedIds)->delete();
            }
        });

        return count($this->upserts) + count($removedIds);
    }
}

upsert() sends one INSERT … ON DUPLICATE KEY UPDATE for up to 500 rows. MySQL uses the unique index on (property_id, source, uid) from scene 12 to decide, row by row, whether it is an insert or an update. Eloquent’s upsert() also fills created_at and updated_at.

Model events don’t fire for an upsert() or a mass delete(). Nothing listens to ExternalBlock events, and this is the trade a bulk write always makes: write bulk only where nothing listens.

The importer registers, then commits

app/Channels/Ical/IcalImporter.phpchanged since scene 12: +9 −23
<?php namespace App\Channels\Ical; use App\Bookings\Stay;use App\Enums\Channel;use App\Models\ExternalBlock;use App\Models\IcalFeed;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Http;use UnexpectedValueException; final class IcalImporter{    /** @return int the number of events in the feed */    /** @return int the number of blocks that changed: 0 when the calendar is the same as last time */    public function sync(IcalFeed $feed): int    {        $ics = Http::timeout(10)->retry(2, 500)->get($feed->url)->throw()->body();   // a timeout throws; it is not "empty"         if (! str_contains($ics, 'BEGIN:VCALENDAR')) {            throw new UnexpectedValueException("Feed {$feed->id} did not return a calendar.");        }         $events = [];        $changes = BlockChanges::for($feed);                            // the feed's blocks, loaded once         foreach ($this->components($ics) as $component) {            $event = $this->eventFrom($feed->source, $component);            if ($event !== null) {                $events[$event->uid] = $event;                $changes->seen($event);                                 // compared in memory, nothing written            }        }         DB::transaction(function () use ($feed, $events): void {                    // all of it, or none of it            foreach ($events as $event) {                ExternalBlock::updateOrCreate(                    ['property_id' => $feed->property_id, 'source' => $feed->source, 'uid' => $event->uid],                    ['kind' => $event->kind, 'starts_on' => $event->stay->checkIn->toDateString(), 'ends_on' => $event->stay->checkOut->toDateString()],                );            }             ExternalBlock::query()                ->where('property_id', $feed->property_id)                ->where('source', $feed->source)                                     // only this channel's blocks                ->whereNotIn('uid', array_keys($events))                ->delete();             $feed->forceFill(['last_synced_at' => now()])->save();        });         return count($events);        $changed = $changes->commit();                                  // only the differences, in one transaction         $feed->forceFill(['last_synced_at' => now()])->save();         return $changed;    }     /** @param array<string, string> $component e.g. ['UID' => '…', 'DTSTART' => '20270710', 'SUMMARY' => 'Reserved'] */
46 unchanged lines private function eventFrom(Channel $source, array $component): ?IcalEvent { if (! isset($component['UID'], $component['DTSTART'], $component['DTEND'])) { return null; // not a usable event: skip it } $kind = match ($source) { Channel::Airbnb => ($component['SUMMARY'] ?? '') === 'Reserved' ? 'reservation' : 'blocked', Channel::BookingCom => 'blocked', // "CLOSED - Not available": the feed doesn't say which it is }; return new IcalEvent( $component['UID'], Stay::fromDates($this->date($component['DTSTART']), $this->date($component['DTEND'])), $kind, ); } /** "20270710" or "20270710T000000Z" → "2027-07-10" */ private function date(string $value): string { return substr($value, 0, 4) . '-' . substr($value, 4, 2) . '-' . substr($value, 6, 2); } /** @return list<array<string, string>> one array per VEVENT, property name => value */ private function components(string $ics): array { $ics = preg_replace('/\r?\n[ \t]/', '', $ics); // unfold lines continued on the next line (RFC 5545) $events = []; $current = null; foreach (preg_split('/\r?\n/', $ics) as $line) { if ($line === 'BEGIN:VEVENT') { $current = []; } elseif ($line === 'END:VEVENT' && $current !== null) { $events[] = $current; $current = null; } elseif ($current !== null && str_contains($line, ':')) { [$name, $value] = explode(':', $line, 2); $current[strtoupper(explode(';', $name)[0])] = $value; // "DTSTART;VALUE=DATE" → "DTSTART" } } return $events; }}

Two events with the same UID in one feed (it happens) register twice; the second simply overwrites the first in $seen and both rows go to upsert(), where the later one wins, exactly as the old loop did.

The fix, part 2: one queued sync per feed, and no push when nothing changed

The faster sync drains the queue; three more lines keep it drained. ShouldBeUniqueUntilProcessing (scene 17) stops the scheduler from queuing a feed that is already waiting. The job moves to the channels queue, so guest emails on default never wait behind a sync again (scene 17 did this for pushes and missed this job). And a sync that changed nothing no longer asks CalendarSync to push the calendar to every channel: the channels already have exactly this calendar.

app/Jobs/SyncIcalFeed.phpchanged since scene 18: +15 −6
<?php namespace App\Jobs; use App\Channels\CalendarSync;use App\Channels\Ical\IcalImporter;use App\Models\IcalFeed;use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Queue\Middleware\WithoutOverlapping; class SyncIcalFeed implements ShouldQueueclass SyncIcalFeed implements ShouldQueue, ShouldBeUniqueUntilProcessing{    use Queueable;     public int $tries = 3;     public int $uniqueFor = 1800;                                       // a lost lock frees itself after 30 minutes     public function __construct(public IcalFeed $feed)    {    }         $this->onQueue('channels');    }     public function uniqueId(): string    {        return (string) $this->feed->id;                                // one waiting sync per feed    }     /** @return list<int> */    public function backoff(): array    {
8 unchanged lines return [60, 300]; } /** @return list<object> */ public function middleware(): array { return [(new WithoutOverlapping("ical-feed-{$this->feed->id}"))->expireAfter(120)]; }
public function handle(IcalImporter $importer, CalendarSync $calendar): void { $importer->sync($this->feed); $calendar->blocksChanged($this->feed->property); // blocks from Airbnb's feed close Booking.com too if ($importer->sync($this->feed) > 0) { $calendar->blocksChanged($this->feed->property); // only a real change goes to the channels and screens } }}

After the deploy: the database part of a sync is about 8 ms when nothing changed and rarely more than 40 ms when something did. What is left is the download, about 0.3 s, so 3,100 feeds take about 16 minutes of worker time per 15-minute cycle, for workers that have 60. The 9,400 queued jobs drain in a quarter of an hour, and since each feed can only be queued once, the queue never holds more than 3,100.

The two overbookings were recorded by scene 18’s overbooking check, which already told the owners; support moves the later guests the same day.

You just wrote the Unit of Work pattern

Unit of WorkKeep track of everything a business operation changes (new, changed and removed objects) and write all of it to the database at the end, in one go.

  • BlockChanges is a small Unit of Work for one sync: seen() registers each event as new, changed or unchanged; commit() works out the removals and writes everything in one transaction.
  • The win is not the transaction, which the old code also had. It is that comparing happens in memory, so writes happen only for real differences, and the writes that do happen are batched.
  • Doctrine’s EntityManager is a full Unit of Work: it tracks every entity you load, and flush() writes all their changes at once. Eloquent has none: save() writes immediately. So in Laravel you write a small, specific one, where a loop of saves is the bottleneck, like this one.

When not to use it

  • A handful of rows: a loop of save() calls is simpler, fires model events, and is fast enough. This sync was fine for months.
  • When other code listens to the model’s events (observers, scene 35): bulk writes skip them.

Laravel inside: what upsert() sends to MySQL

One statement for many rows. uniqueBy matters on databases that need to be told the conflict target; MySQL always uses the table’s unique indexes.

the SQL for two rows
INSERT INTO external_blocks (property_id, source, uid, kind, starts_on, ends_on, created_at, updated_at)
VALUES
  (412, 'booking_com', 'bk-20270710', 'blocked', '2027-07-10', '2027-07-11', '2027-06-01 10:00:00', '2027-06-01 10:00:00'),
  (412, 'booking_com', 'bk-20270711', 'blocked', '2027-07-11', '2027-07-12', '2027-06-01 10:00:00', '2027-06-01 10:00:00')
ON DUPLICATE KEY UPDATE
  kind = VALUES(kind), starts_on = VALUES(starts_on), ends_on = VALUES(ends_on), updated_at = VALUES(updated_at)

created_at is only set for rows that are really inserted: Laravel leaves it out of the UPDATE part, so an updated block keeps the day it first appeared.

TestsNo writes for an unchanged feed, every kind of change in one go, other channels untouched, one queued sync per feed
tests/Feature/IcalAtScaleTest.phpnew file
<?php

use App\Channels\Ical\IcalImporter;
use App\Enums\Channel;
use App\Jobs\PushAvailability;
use App\Jobs\SyncIcalFeed;
use App\Models\ChannelListing;
use App\Models\ExternalBlock;
use App\Models\IcalFeed;
use App\Models\Property;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;

function icsFeed(string ...$events): string
{
    return "BEGIN:VCALENDAR\r\n" . implode('', $events) . "END:VCALENDAR\r\n";
}

function icsEvent(string $uid, string $start, string $end): string
{
    return "BEGIN:VEVENT\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nUID:{$uid}\r\nSUMMARY:CLOSED - Not available\r\nEND:VEVENT\r\n";
}

/** @return list<string> every INSERT, UPDATE or DELETE on external_blocks while $run runs */
function blockWrites(Closure $run): array
{
    $writes = [];
    DB::listen(function (QueryExecuted $query) use (&$writes): void {
        if (preg_match('/^(insert|update|delete)\b.*external_blocks/i', $query->sql)) {
            $writes[] = $query->sql;
        }
    });
    $run();

    return $writes;
}

beforeEach(function () {
    $this->property = Property::factory()->create();
    $this->feed = IcalFeed::forceCreate(['property_id' => $this->property->id, 'source' => Channel::BookingCom, 'url' => 'https://booking.test/412.ics']);
});

it('writes nothing when the feed hasn’t changed', function () {
    $events = array_map(fn (int $day): string => icsEvent("bk-{$day}", sprintf('202707%02d', $day), sprintf('202707%02d', $day + 1)), range(1, 30));
    Http::fake(['booking.test/*' => Http::response(icsFeed(...$events))]);
    app(IcalImporter::class)->sync($this->feed);                              // the first sync saves all 30

    $writes = blockWrites(fn () => expect(app(IcalImporter::class)->sync($this->feed))->toBe(0));

    expect($writes)->toBe([]);                                               // the incident: 30 events, no writes at all
});

it('adds, changes and removes blocks in one go', function () {
    Http::fake(['booking.test/*' => Http::sequence()
        ->push(icsFeed(icsEvent('a', '20270701', '20270703'), icsEvent('b', '20270710', '20270712')))
        ->push(icsFeed(icsEvent('b', '20270710', '20270714'), icsEvent('c', '20270720', '20270721')))]);   // b longer, c new, a gone

    app(IcalImporter::class)->sync($this->feed);
    $writes = blockWrites(fn () => expect(app(IcalImporter::class)->sync($this->feed))->toBe(3));

    expect(ExternalBlock::orderBy('uid')->get()->map(fn (ExternalBlock $block): string => "{$block->uid}:{$block->ends_on->toDateString()}")->all())
        ->toBe(['b:2027-07-14', 'c:2027-07-21'])
        ->and($writes)->toHaveCount(2);                                      // one upsert, one delete
});

it('never touches another channel’s blocks', function () {
    ExternalBlock::create(['property_id' => $this->property->id, 'source' => Channel::Airbnb, 'uid' => 'airbnb-1', 'kind' => 'reservation', 'starts_on' => '2027-07-01', 'ends_on' => '2027-07-04']);
    Http::fake(['booking.test/*' => Http::response(icsFeed())]);              // an empty Booking.com calendar

    app(IcalImporter::class)->sync($this->feed);

    expect(ExternalBlock::pluck('uid')->all())->toBe(['airbnb-1']);
});

it('queues one sync per feed, however often the scheduler runs', function () {
    Queue::fake();

    SyncIcalFeed::dispatch($this->feed);
    SyncIcalFeed::dispatch($this->feed);                                       // the next 15-minute run, before the first was processed

    Queue::assertPushedTimes(SyncIcalFeed::class, 1);
});

it('pushes to the channels only when the feed changed something', function () {
    ChannelListing::forceCreate(['property_id' => $this->property->id, 'channel' => Channel::Airbnb, 'external_listing_id' => '41793625']);
    Http::fake(['booking.test/*' => Http::response(icsFeed(icsEvent('a', '20270701', '20270703')))]);
    app(IcalImporter::class)->sync($this->feed);
    Queue::fake();

    app()->call([new SyncIcalFeed($this->feed), 'handle']);                    // same feed as before

    Queue::assertNotPushed(PushAvailability::class);
});

blockWrites() counts the statements that reach MySQL, so the first test fails if anyone brings back a write per event, even one that writes the same values.

Follow-up, the same afternoon: deadlocks between two feeds of one cottage

Syncs are fast now, so the queue runs many at once. Within hours, a new error shows up that the slow sync never had.

#opsWednesday 15:40

SentrySQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction in SyncIcalFeed. 34 events in the last hour.

Jonas · developerAlways a property with two feeds, Airbnb and Booking.com, and always two jobs for that property running in the same second. The retry usually works a minute later; 3 jobs used up all their tries and failed.

Karim · developerBefore today one sync took a second or more and two of them rarely met. Now the scheduler queues 3,100 jobs at :00, :15, :30 and :45, and both feeds of a cottage start together.

The broken code

The overlap guard is per feed. Two feeds of the same property are two keys, so their transactions run side by side on the same rows of the same index:

app/Jobs/SyncIcalFeed.php (the middleware, as the fix above left it)the bug
return [(new WithoutOverlapping("ical-feed-{$this->feed->id}"))->expireAfter(120)];   // the bug: per feed, while the rows are per property

Both transactions write external_blocks rows of the same property through the same unique index, (property_id, source, uid). To see why that can deadlock, you need to know what MySQL locks besides the rows themselves.

What REPEATABLE READ locks: rows and the gaps between them

MySQL’s default isolation level is REPEATABLE READ. Every plain SELECT in a transaction reads one consistent snapshot, taken at the first read, so the same query returns the same rows until commit. Locking reads and writes go further: to stop a phantom (a new row appearing inside a range you already read), InnoDB locks not only the index records it touches but also the gap before each one. A record plus its gap is a *next-key lock*.

Gap locks don’t conflict with each other: two transactions can hold the same gap. What waits for a gap lock is an insert into that gap. So two transactions that each hold a gap and each want to insert into the other’s gap wait for each other forever. InnoDB detects the cycle, rolls one back with error 1213, and lets the other finish.

INSERT … ON DUPLICATE KEY UPDATE (Laravel’s upsert()) takes an exclusive next-key lock on every duplicate it finds, and inserts the rest. Two batches for the same property, one per feed, each lock records and gaps around that property’s part of the unique index and insert new UIDs next to them: the pattern above, many times a minute.

See a gap lock yourself

Two mysql sessions on a copy of the database. Property 412 has blocks with UIDs a and c from Airbnb:

two mysql sessions (an experiment, not a test)
-- session 1
start transaction;
select id from external_blocks where property_id = 412 and source = 'airbnb' and uid = 'b' for update;   -- no row 'b': locks the gap between 'a' and 'c'

-- session 2
insert into external_blocks (property_id, source, uid, kind, starts_on, ends_on, created_at, updated_at)
values (412, 'airbnb', 'b', 'blocked', '2027-07-01', '2027-07-02', now(), now());                      -- waits: 'b' is inside the locked gap

-- session 3: who holds what
select engine_transaction_id, index_name, lock_mode, lock_status, lock_data
from performance_schema.data_locks where object_name = 'external_blocks';
-- … external_blocks_property_id_source_uid_unique  X,GAP                     GRANTED  412, 'airbnb', 'c', 77
-- … external_blocks_property_id_source_uid_unique  X,GAP,INSERT_INTENTION    WAITING  412, 'airbnb', 'c', 77

-- now repeat with session 1 at READ COMMITTED:
set transaction isolation level read committed;   -- before start transaction: the same select locks no gap, and the insert goes through

That last line is why "switch to READ COMMITTED" is a common reply to deadlocks. It removes gap locks for searches and index scans, but MySQL keeps them for duplicate-key checks, which is exactly what upsert() does. It would make these deadlocks rarer, not impossible, and it changes what every other transaction on the connection may see. The fix is to stop two writers meeting at all.

How the fix works, in one picture

Before

Airbnb feedupsertgap lockBooking.com feedupsertgap locksame cottage, same second: deadlock

Two feeds of one property wrote the same index at once, each holding a gap the other needed.

After

Airbnb feedlock: property 412upsert, commitBooking.com feedwaits 10 supsert, commit

One sync per property at a time; the second waits seconds instead of deadlocking.

The fix: one sync per property at a time, and a retry for the rare deadlock left

The overlap key becomes the property. The second feed’s job finds the lock taken and is released back to the queue for 10 seconds; by then the first has committed. A property has at most three feeds, so the delay is seconds, and nothing waits on a lock inside MySQL.

Deadlocks can still happen elsewhere: a booking import (scene 15) can touch the same property. Laravel already knows what to do: DB::transaction($callback, attempts: 3) runs the callback again when the database reports a deadlock or a lost lock, and throws only after the third try. Retrying a deadlock is what MySQL’s message asks for; the transaction is all-or-nothing, so it is safe to run again.

app/Jobs/SyncIcalFeed.phpchanged since the version above: +4 −2
13 unchanged lines<?php namespace App\Jobs; use App\Channels\CalendarSync;use App\Channels\Ical\IcalImporter;use App\Models\IcalFeed;use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Queue\Middleware\WithoutOverlapping; class SyncIcalFeed implements ShouldQueue, ShouldBeUniqueUntilProcessing
{ use Queueable; public int $tries = 3; public int $tries = 5; // releases while another feed syncs count as tries public int $uniqueFor = 1800; // a lost lock frees itself after 30 minutes
16 unchanged lines public function __construct(public IcalFeed $feed) { $this->onQueue('channels'); } public function uniqueId(): string { return (string) $this->feed->id; // one waiting sync per feed } /** @return list<int> */ public function backoff(): array { return [60, 300]; }
/** @return list<object> */ public function middleware(): array { return [(new WithoutOverlapping("ical-feed-{$this->feed->id}"))->expireAfter(120)]; return [(new WithoutOverlapping("ical-property-{$this->feed->property_id}")) // all feeds of a property, one at a time ->releaseAfter(10) ->expireAfter(120)]; } public function handle(IcalImporter $importer, CalendarSync $calendar): void
6 unchanged lines { if ($importer->sync($this->feed) > 0) { $calendar->blocksChanged($this->feed->property); // only a real change goes to the channels and screens } }}

releaseAfter(10) puts the job back with a 10-second delay instead of dropping it; without it, WithoutOverlapping releases with no delay and the job spins. Each release counts as an attempt, hence $tries = 5.

app/Channels/Ical/BlockChanges.phpchanged since the version above: +4 −1
9 unchanged lines<?php namespace App\Channels\Ical; use App\Models\ExternalBlock;use App\Models\IcalFeed;use Illuminate\Support\Collection;use Illuminate\Support\Facades\DB;
/** Everything one sync changes in a feed's blocks, collected first and written in one go. */final class BlockChanges{ /** How often the write runs again after a deadlock before the job fails. */ public const ATTEMPTS = 3; /** @var list<array<string, string|int>> rows to insert or update */ private array $upserts = [];
62 unchanged lines /** @var array<string, true> the UIDs the feed still contains */ private array $seen = []; /** @param Collection<string, ExternalBlock> $current the feed's blocks now, by UID */ private function __construct( private readonly IcalFeed $feed, private readonly Collection $current, ) { } public static function for(IcalFeed $feed): self { $current = ExternalBlock::query() ->where('property_id', $feed->property_id) ->where('source', $feed->source) // only this channel's blocks (scene 12) ->get() ->keyBy('uid'); // one query for the whole feed return new self($feed, $current); } /** Register one event of the new feed: new, changed or the same. Nothing is written yet. */ public function seen(IcalEvent $event): void { $this->seen[$event->uid] = true; $block = $this->current->get($event->uid); $startsOn = $event->stay->checkIn->toDateString(); $endsOn = $event->stay->checkOut->toDateString(); if ($block !== null && $block->kind === $event->kind && $block->starts_on->toDateString() === $startsOn && $block->ends_on->toDateString() === $endsOn) { return; // identical: nothing to write } $this->upserts[] = [ 'property_id' => $this->feed->property_id, 'source' => $this->feed->source->value, // raw rows: the enum's value, not the enum 'uid' => $event->uid, 'kind' => $event->kind, 'starts_on' => $startsOn, 'ends_on' => $endsOn, ]; } /** Write every registered change in one short transaction. @return int the number of rows inserted, updated or deleted */ public function commit(): int { $removedIds = $this->current ->reject(fn (ExternalBlock $block): bool => isset($this->seen[$block->uid])) ->pluck('id') ->all(); if ($this->upserts === [] && $removedIds === []) { return 0; // the usual case: no transaction at all } DB::transaction(function () use ($removedIds): void { foreach (array_chunk($this->upserts, 500) as $rows) { // a year of new blocks: still a few statements ExternalBlock::upsert($rows, uniqueBy: ['property_id', 'source', 'uid'], update: ['kind', 'starts_on', 'ends_on']); }
if ($removedIds !== []) { ExternalBlock::whereKey($removedIds)->delete(); } }); }, attempts: self::ATTEMPTS); // a deadlock rolls everything back, so running it again is safe return count($this->upserts) + count($removedIds); }}

The callback only uses what BlockChanges computed before the transaction, so a second attempt writes exactly the same rows. A callback that sent an email or dispatched a job without afterCommit() would do it twice; this one doesn’t.

BeforeAfter
Deadlocks per hour340 in the next week (the retry never needed)
Two feeds of one propertyIn parallel, on the same indexOne after the other, 10 s apart at most
Failed SyncIcalFeed jobs3 in one hournone
TestsAll feeds of a property share one overlap key
tests/Feature/IcalOverlapTest.phpnew file
<?php

use App\Enums\Channel;
use App\Jobs\SyncIcalFeed;
use App\Models\IcalFeed;
use App\Models\Property;
use Illuminate\Queue\Middleware\WithoutOverlapping;

it('lets only one feed of a property sync at a time', function () {
    $cottage = Property::factory()->create();
    $airbnb = IcalFeed::forceCreate(['property_id' => $cottage->id, 'source' => Channel::Airbnb, 'url' => 'https://airbnb.test/1.ics']);
    $bookingCom = IcalFeed::forceCreate(['property_id' => $cottage->id, 'source' => Channel::BookingCom, 'url' => 'https://booking.test/1.ics']);
    $elsewhere = IcalFeed::forceCreate(['property_id' => Property::factory()->create()->id, 'source' => Channel::Airbnb, 'url' => 'https://airbnb.test/2.ics']);

    $key = fn (IcalFeed $feed): string => collect((new SyncIcalFeed($feed))->middleware())
        ->first(fn (object $middleware): bool => $middleware instanceof WithoutOverlapping)->key;

    expect($key($airbnb))->toBe($key($bookingCom))                               // the incident: two keys for one cottage
        ->and($key($elsewhere))->not->toBe($key($airbnb));                        // other properties still run in parallel
});

Mutation: put ical-feed-{$this->feed->id} back and the test fails, which is the incident’s cause.

There is no test for the retry. attempts: 3 is Laravel’s behaviour, not ours, and inside RefreshDatabase every transaction is nested in the test’s own, where Laravel deliberately rethrows a deadlock instead of retrying: only the outermost transaction can safely start again. The experiment above shows the lock itself; the week of zero deadlocks shows the fix.

Remember

  • Work out every change in memory, then write once: upsert() in chunks and one delete.
  • Writers of the same rows take turns (WithoutOverlapping per property) instead of deadlocking.

Calendars are minutes old again, and two feeds of one cottage take turns. Next, the busiest day of the year: search slows to eight seconds at the 99th percentile.