Course › Day 3 · Channels › Scene 17 of 49 · 35 min
642 pushes queued in one minute
State instead of changes, one request per calendar, ShouldBeUniqueUntilProcessing, WithoutOverlapping, two Redis queues, Horizon, retry_after, the worker loop
On this page
#incidentsMonday 07:55
Alert · queuesQueue default: 642 jobs waiting, oldest 25 minutes. Guest emails are stuck behind them.
Karim · developerBooking.com was down overnight. At 07:30 the poll (scene 15) caught up 642 new, changed and cancelled reservations at once, and every import queued one push to the property’s Airbnb listing: 642 jobs. And Ahmed says two nights that are booked show as open on Airbnb.
The broken code
// one job per change, per listing, describing the change
foreach ($property->channelListings as $listing) {
CloseChannelDates::dispatch($listing, $booking->stay)->afterCommit();
}
// CancelBooking: the same, with $close = false
Each job carries a change: "close 1–4 August", "open 2–3 August". 642 imports produced 642 of them, and they all wait in the one queue that also sends guest emails.
Worse, changes only make sense in order, and queues don’t promise order. Workers run jobs in parallel and retries come back later, so an "open" that was queued first can finish after the "close" that should have replaced it. That’s how booked nights showed as open on Airbnb.
How the fix works, in one picture
Before
Every change queued its own push, in front of guest emails.
After
A unique job per listing sends the whole calendar in one request; a burst becomes one push per listing, on its own queue.
The fix, part 1: push the state, not the change
Instead of "what changed", each push sends how the calendar is now: every night for the next 12 months, grouped into runs of open and closed nights, read fresh from the database when the job runs. A push like that can run twice, late, or out of order, and the result is always correct, because the last one to run sends the latest truth.
<?php
namespace App\Channels;
use App\Bookings\Stay;
use App\Models\Property;
use Carbon\CarbonImmutable;
final class AvailabilityRuns
{
/** @return list<array{nights: Stay, open: bool}> consecutive nights grouped by open/closed */
public function for(Property $property, CarbonImmutable $from, int $days): array
{
$window = Stay::fromDates($from->toDateString(), $from->addDays($days)->toDateString());
$closed = []; // 'Y-m-d' => true for every occupied night
$occupy = function (CarbonImmutable $first, CarbonImmutable $end) use (&$closed): void {
for ($night = $first; $night->lessThan($end); $night = $night->addDay()) {
$closed[$night->toDateString()] = true;
}
};
foreach ($property->bookings()->overlapping($window)->get(['check_in', 'check_out']) as $booking) {
$occupy($booking->check_in, $booking->check_out); // pending and confirmed only (scene 3)
}
foreach ($property->externalBlocks()->overlapping($window)->get(['starts_on', 'ends_on']) as $block) {
$occupy($block->starts_on, $block->ends_on); // scene 12
}
$runs = [];
$start = $window->checkIn;
for ($night = $window->checkIn; $night->lessThan($window->checkOut); $night = $night->addDay()) {
$next = $night->addDay();
$isOpen = ! isset($closed[$night->toDateString()]);
if ($next->equalTo($window->checkOut) || $isOpen !== ! isset($closed[$next->toDateString()])) {
$runs[] = ['nights' => Stay::fromDates($start->toDateString(), $next->toDateString()), 'open' => $isOpen];
$start = $next; // the next run starts tomorrow
}
}
return $runs;
}
}
One request per push
A year with 30 bookings is about 60 runs. Sent one call at a time, that is about 60 calls per push: a whole minute of a channel’s budget at scene 16’s limit, for every listing in a burst. Both channels accept many date ranges in one request (Airbnb a list of operations, Booking.com several <date> elements), so the interface stops describing one change and describes the whole calendar:
7 unchanged lines
<?php namespace App\Channels; use App\Bookings\Stay;use App\Models\ChannelListing;use Carbon\CarbonImmutable; interface ChannelApi{ /** Make these nights unbookable on the channel. Throws ChannelRequestFailed when the channel refuses. */ public function closeDates(ChannelListing $listing, Stay $nights): void; public function openDates(ChannelListing $listing, Stay $nights): void; /** * Send the listing's calendar as it is now, in one request: every run of nights, open or closed. * Throws ChannelRequestFailed when the channel refuses. * * @param non-empty-list<array{nights: Stay, open: bool}> $runs */ public function updateCalendar(ChannelListing $listing, array $runs): void; /** @return iterable<ChannelReservation> every reservation of the listing modified since $since */ public function reservationsUpdatedSince(ChannelListing $listing, CarbonImmutable $since): iterable;}
closeDates() and openDates() go: from now on nothing sends a single change. PHP refuses to load a class that implements the interface without updateCalendar(), so both adapters, the rate limiter and the test fake from scene 16 change below, and none can be forgotten.
<?php namespace App\Channels\Airbnb; use App\Bookings\Stay;use App\Channels\ChannelApi;use App\Channels\ChannelRequestFailed;use App\Enums\Channel;9 unchanged lines
use App\Models\ChannelListing;use Carbon\CarbonImmutable;use Illuminate\Support\Facades\Http; final readonly class AirbnbApi implements ChannelApi{ public function __construct( private AirbnbTokens $tokens, private string $baseUrl, ) { } public function closeDates(ChannelListing $listing, Stay $nights): void { $this->setAvailability($listing, $nights, 'unavailable'); } public function openDates(ChannelListing $listing, Stay $nights): void { $this->setAvailability($listing, $nights, 'available'); } private function setAvailability(ChannelListing $listing, Stay $nights, string $availability): void { public function updateCalendar(ChannelListing $listing, array $runs): void { $operations = array_map(fn (array $run): array => [ 'start_date' => $run['nights']->checkIn->toDateString(), 'end_date' => $run['nights']->checkOut->subDay()->toDateString(), // Airbnb counts nights inclusively 'availability' => $run['open'] ? 'available' : 'unavailable', ], $runs); $response = Http::withToken($this->tokens->for($listing)) ->timeout(10) ->retry([200, 600], when: ChannelRequestFailed::worthRetrying(...), throw: false) // two more tries, 200 and 600 ms apart ->acceptJson() ->put("{$this->baseUrl}/calendars/{$listing->external_listing_id}", [ 'start_date' => $nights->checkIn->toDateString(), 'end_date' => $nights->checkOut->subDay()->toDateString(), // Airbnb counts nights inclusively 'availability' => $availability, ]); ->put("{$this->baseUrl}/calendars/{$listing->external_listing_id}", ['operations' => $operations]); if ($response->failed()) { throw ChannelRequestFailed::from(Channel::Airbnb, $response); // never a silent 401 again28 unchanged lines
} } public function reservationsUpdatedSince(ChannelListing $listing, CarbonImmutable $since): iterable { $mapper = new AirbnbReservationMapper(); $cursor = null; do { $response = Http::withToken($this->tokens->for($listing))->timeout(10)->acceptJson() ->get("{$this->baseUrl}/reservations", array_filter([ 'listing_id' => $listing->external_listing_id, 'updated_since' => $since->toIso8601String(), 'cursor' => $cursor, ])); if ($response->failed()) { throw ChannelRequestFailed::from(Channel::Airbnb, $response); } foreach ($response->json('reservations') as $reservation) { yield $mapper->reservation(['reservation' => $reservation]); // the same mapper as the webhooks } $cursor = $response->json('next_cursor'); } while ($cursor !== null); }}
The retry from scene 16 stays safe: repeating this request sends the same calendar again.
Booking.com, one <date> per run in one XML request:
<?php namespace App\Channels\BookingCom; use App\Bookings\Stay;use App\Channels\ChannelApi;use App\Channels\ChannelRequestFailed;use App\Enums\Channel;10 unchanged lines
use App\Models\ChannelListing;use Carbon\CarbonImmutable;use Illuminate\Support\Facades\Http; final readonly class BookingComApi implements ChannelApi{ public function __construct( private string $baseUrl, private string $username, private string $password, ) { } public function closeDates(ChannelListing $listing, Stay $nights): void { $this->send($listing, $nights, closed: true); } public function openDates(ChannelListing $listing, Stay $nights): void { $this->send($listing, $nights, closed: false); } private function send(ChannelListing $listing, Stay $nights, bool $closed): void { public function updateCalendar(ChannelListing $listing, array $runs): void { $dates = array_map(fn (array $run): string => sprintf( '<date from="%s" to="%s"><closed>%d</closed></date>', $run['nights']->checkIn->toDateString(), $run['nights']->checkOut->subDay()->toDateString(), // the last night, inclusive $run['open'] ? 0 : 1, ), $runs); $xml = sprintf( '<request><hotel_id>%s</hotel_id><date from="%s" to="%s"><closed>%d</closed></date></request>', '<request><hotel_id>%s</hotel_id>%s</request>', htmlspecialchars($listing->external_listing_id, ENT_XML1), // never trust a value inside XML $nights->checkIn->toDateString(), $nights->checkOut->subDay()->toDateString(), $closed ? 1 : 0, implode('', $dates), // every run of the year, one request ); $response = Http::withBasicAuth($this->username, $this->password)36 unchanged lines
->timeout(10) ->retry([200, 600], when: ChannelRequestFailed::worthRetrying(...), throw: false) // two more tries, 200 and 600 ms apart ->withBody($xml, 'text/xml') ->post("{$this->baseUrl}/hotels/xml/availability"); // Booking.com-style XML APIs can answer 200 with an error inside the body if ($response->failed() || str_contains($response->body(), '<error')) { throw ChannelRequestFailed::from(Channel::BookingCom, $response); } } public function reservationsUpdatedSince(ChannelListing $listing, CarbonImmutable $since): iterable { $mapper = new BookingComReservationMapper(); $page = 1; do { $response = Http::withBasicAuth($this->username, $this->password)->timeout(10)->acceptJson() ->get("{$this->baseUrl}/hotels/json/reservations", [ 'hotel_id' => $listing->external_listing_id, 'last_change' => $since->utc()->format('Y-m-d H:i:s'), 'page' => $page, ]); if ($response->failed()) { throw ChannelRequestFailed::from(Channel::BookingCom, $response); } foreach ($response->json('reservations') as $reservation) { yield $mapper->reservation(['reservation' => $reservation]); // the same mapper as the webhooks } $page++; } while ($response->json('has_more') === true); }}
The rate limiter wraps the new method. One push is now one count against the channel’s limit:
<?php namespace App\Channels; use App\Bookings\Stay;use App\Models\ChannelListing;use Carbon\CarbonImmutable;use Closure;8 unchanged lines
use Illuminate\Support\Facades\RateLimiter; final readonly class ThrottledChannelApi implements ChannelApi{ public function __construct( private ChannelApi $inner, private string $channel, private int $perMinute, ) { } public function closeDates(ChannelListing $listing, Stay $nights): void { $this->throttle(fn () => $this->inner->closeDates($listing, $nights)); } public function openDates(ChannelListing $listing, Stay $nights): void { $this->throttle(fn () => $this->inner->openDates($listing, $nights)); public function updateCalendar(ChannelListing $listing, array $runs): void { $this->throttle(fn () => $this->inner->updateCalendar($listing, $runs)); // one push, one request, one count } public function reservationsUpdatedSince(ChannelListing $listing, CarbonImmutable $since): iterable16 unchanged lines
{ $this->throttle(fn () => null); // counts the first page; polls are rare return $this->inner->reservationsUpdatedSince($listing, $since); } private function throttle(Closure $call): void { $key = "channel-api:{$this->channel}"; if (RateLimiter::hit($key, decaySeconds: 60) > $this->perMinute) { // count first: one atomic increment in Redis throw ChannelRateLimited::wait($this->channel, RateLimiter::availableIn($key)); } $call(); }}
At Airbnb’s 60 a minute, the incident’s 642 imports now cost at most 642 requests, one per listing that changed: about eleven minutes of budget. At 60 calls per push they would have cost about eleven hours.
The fix, part 2: one command, coalesced
The job is a command: one object that holds everything needed to do one thing ("bring this listing up to date"), and can be queued, retried and logged as a unit.
Because it always sends the current state, ten pushes waiting for the same listing are worth exactly one. ShouldBeUniqueUntilProcessing takes a Redis lock per listing when the job is dispatched; while one push is waiting, further dispatches are dropped. The lock is released when the push starts, so a change that happens during a push queues one more, which will see it. WithoutOverlapping makes that next push wait until the running one ends.
<?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::table('channel_listings', function (Blueprint $table) {
$table->timestamp('last_pushed_at')->nullable();
$table->text('last_push_error')->nullable(); // shown to the host: "Airbnb is not in sync"
});
}
};
<?php
namespace App\Jobs;
use App\Channels\AvailabilityRuns;
use App\Channels\ChannelManager;
use App\Channels\ChannelRateLimited;
use App\Models\ChannelListing;
use App\Models\Property;
use DateTimeInterface;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Throwable;
class PushAvailability implements ShouldQueue, ShouldBeUniqueUntilProcessing
{
use Queueable;
public const DAYS = 365;
public int $uniqueFor = 900; // a stuck lock frees itself after 15 minutes
public function __construct(public ChannelListing $listing)
{
$this->onQueue('channels'); // never in front of guest emails again
}
/** Dispatch one push per listing of the property, after the current transaction commits. */
public static function forProperty(Property $property): void
{
foreach ($property->channelListings as $listing) {
self::dispatch($listing)->afterCommit();
}
}
public function uniqueId(): string
{
return (string) $this->listing->id; // one waiting push per listing
}
/** @return list<object> */
public function middleware(): array
{
return [(new WithoutOverlapping("push-listing-{$this->listing->id}"))->releaseAfter(30)->expireAfter(600)];
}
public function retryUntil(): DateTimeInterface
{
return now()->addHours(2);
}
/** @return list<int> */
public function backoff(): array
{
return [30, 120, 300, 900];
}
public function handle(ChannelManager $channels, AvailabilityRuns $runs): void
{
$api = $channels->for($this->listing->channel)->api();
try {
$api->updateCalendar($this->listing, $runs->for($this->listing->property, now()->startOfDay(), self::DAYS)); // the year, one request
} catch (ChannelRateLimited $e) {
$this->release($e->retryAfter); // scene 16
return;
}
$this->listing->forceFill(['last_pushed_at' => now(), 'last_push_error' => null])->save();
}
public function failed(Throwable $exception): void
{
$this->listing->forceFill(['last_push_error' => $exception->getMessage()])->save();
}
}
Every caller pushes the state
The four places that change the calendar call PushAvailability::forProperty(). Confirming:
<?php namespace App\Bookings; use App\Enums\PaymentStatus;use App\Jobs\CloseChannelDates;use App\Jobs\PushAvailability;use App\Models\Booking;use App\Models\Payment;use App\Notifications\BookingConfirmed;17 unchanged lines
use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Notification; final class BookingConfirmation{ public function confirm(Booking $booking, Payment $payment): void { DB::transaction(function () use ($booking, $payment): void { $booking = Booking::whereKey($booking->id)->lockForUpdate()->firstOrFail(); // fresh, and locked if (! $booking->state()->confirm($booking)) { // step 1: the state decides return; // already confirmed: nothing else to do } $payment->status = PaymentStatus::Succeeded; // step 2 $payment->save(); Notification::route('mail', $booking->guest_email) // step 3, after the commit ->notify((new BookingConfirmed($booking))->afterCommit()); foreach ($booking->property->channelListings as $listing) { // step 4: close the nights on every channel CloseChannelDates::dispatch($listing, $booking->stay)->afterCommit(); } PushAvailability::forProperty($booking->property); // step 4: every channel gets the calendar as it is now }); }}
Cancelling:
<?php namespace App\Bookings; use App\Enums\PaymentStatus;use App\Jobs\CloseChannelDates;use App\Jobs\PushAvailability;use App\Jobs\RefundCancelledBooking;use App\Models\Booking;use App\Money\Money;12 unchanged lines
use Illuminate\Support\Facades\DB; final class CancelBooking{ /** @return Money the amount that will be refunded */ public function handle(Booking $booking): Money { return DB::transaction(function () use ($booking): Money { $booking = Booking::whereKey($booking->id)->lockForUpdate()->firstOrFail(); $nothing = Money::zero($booking->total->currency); if (! $booking->state()->cancel($booking)) { // scene 9: already cancelled return $nothing; } foreach ($booking->property->channelListings as $listing) { // the nights are free again everywhere CloseChannelDates::dispatch($listing, $booking->stay, close: false)->afterCommit(); } PushAvailability::forProperty($booking->property); // the nights are free again everywhere $payment = $booking->payments() ->where('status', PaymentStatus::Succeeded)19 unchanged lines
->whereNotNull('provider_payment_id') // card payments; bank transfers go back by hand ->latest('id') ->first(); if ($payment === null) { return $nothing; } $hours = (int) floor(now()->diffInHours($booking->stay->checkInAt($booking->property), false)); $refund = $booking->refundPolicy()->refundFor(Money::of($payment->amount_cents, $payment->currency), $hours); if ($refund->amount > 0) { RefundCancelledBooking::dispatch($payment, $refund)->afterCommit(); } return $refund; }); }}
An expired hold:
<?php namespace App\Console\Commands; use App\Enums\BookingStatus;use App\Jobs\CloseChannelDates;use App\Jobs\PushAvailability;use App\Models\Booking;use Illuminate\Console\Command;use Illuminate\Support\Facades\DB;20 unchanged lines
class ExpireHolds extends Command{ protected $signature = 'bookings:expire-holds'; protected $description = 'Expire pending bookings whose hold has ended'; public function handle(): void { Booking::query() ->where('status', BookingStatus::Pending) ->where('expires_at', '<=', now()) ->lazyById() ->each(function (Booking $booking): void { DB::transaction(function () use ($booking): void { $booking = Booking::whereKey($booking->id)->lockForUpdate()->firstOrFail(); if ($booking->status !== BookingStatus::Pending) { // a payment may have won the race return; } $booking->state()->expire($booking); foreach ($booking->property->channelListings as $listing) { CloseChannelDates::dispatch($listing, $booking->stay, close: false)->afterCommit(); } PushAvailability::forProperty($booking->property); }); }); }}
And the channel import, whose 642 reservations started the incident. Now they queue at most one push per listing:
<?php namespace App\Channels; use App\Enums\BookingStatus;use App\Jobs\CloseChannelDates;use App\Jobs\PushAvailability;use App\Models\Booking;use App\Models\ChannelListing;use App\Models\Property;37 unchanged lines
use Illuminate\Support\Facades\DB; final class ImportChannelReservation{ /** @return bool true when the reservation was applied, false when it was older than what we have */ public function handle(ChannelReservation $reservation): bool { $listing = ChannelListing::query() ->where('channel', $reservation->channel) ->where('external_listing_id', $reservation->externalListingId) ->firstOrFail(); return DB::transaction(function () use ($reservation, $listing): bool { Property::whereKey($listing->property_id)->lockForUpdate()->firstOrFail(); // one change per property at a time $booking = Booking::query() ->where('channel', $reservation->channel) ->where('external_id', $reservation->externalId) ->lockForUpdate() ->first() ?? new Booking(); if ($booking->exists && $booking->external_version >= $reservation->version) { return false; // older or the same: already applied something newer } $booking->forceFill([ 'property_id' => $listing->property_id, 'channel' => $reservation->channel, 'external_id' => $reservation->externalId, 'external_version' => $reservation->version, 'status' => $reservation->status, // the channel decides; our own State rules (scene 9) guard our actions 'guest_name' => $reservation->guestName, 'guest_email' => $reservation->guestEmail, 'guests' => $reservation->guests, 'stay' => $reservation->stay, 'total' => $reservation->total, 'confirmed_at' => $booking->confirmed_at ?? now(), 'cancelled_at' => $reservation->status === BookingStatus::Cancelled ? ($booking->cancelled_at ?? now()) : null, ])->save(); foreach ($booking->property->channelListings as $other) { // tell the other channels if ($other->channel !== $reservation->channel) { CloseChannelDates::dispatch($other, $booking->stay, close: $booking->status !== BookingStatus::Cancelled)->afterCommit(); } } PushAvailability::forProperty($booking->property); // one coalesced push per listing, not one per change return true; }); }}
CloseChannelDates has no callers left. Delete it and its test:
rm app/Jobs/CloseChannelDates.php tests/Feature/CloseChannelDatesTest.php
The fix, part 3: queues on Redis, run by Horizon
Two queues: default for guest-facing work (emails, payments) and channels for pushes, each with its own workers, so a flood on one never delays the other. Horizon runs and supervises the workers, restarts them when they die, and shows throughput, wait times and failed jobs in a dashboard.
One rule ties the two files together: a worker’s timeout must be shorter than the queue’s retry_after. Redis hands a job to another worker if it has been reserved for retry_after seconds without finishing. A job allowed to run longer than that runs twice, at the same time.
Install Horizon. horizon:install creates config/horizon.php:
composer require laravel/horizon
php artisan horizon:install
In config/queue.php, replace the redis entry inside connections with this one. The other connections stay as they are:
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 180, // longer than the slowest job's timeout (120 below)
'block_for' => 5, // wait up to 5 s for a job instead of polling Redis in a tight loop
'after_commit' => true, // every dispatch waits for the open transaction to commit
],
In config/horizon.php, replace the whole environments array with this one. Everything else in the file stays as Horizon created it:
'environments' => [
'production' => [
'guests' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'auto',
'minProcesses' => 2,
'maxProcesses' => 10,
'tries' => 0, // the jobs decide: $tries, retryUntil()
'timeout' => 120,
],
'channels' => [
'connection' => 'redis',
'queue' => ['channels'],
'maxProcesses' => 4, // more workers wouldn't help: the channels' limits are the limit
'tries' => 0,
'timeout' => 60, // a push is one request: three tries of 10 s at most
],
],
],
In production, php artisan horizon runs under Supervisor, and every deploy ends with php artisan horizon:terminate so workers restart on the new code (scene 45).
You just met Command and Command Bus
CommandA request turned into an object: everything needed to perform one action, which can then be queued, retried, logged or undone.
Command BusOne dispatcher that takes any command and gets it executed: now, or through a queue. Callers only say what should happen.
PushAvailabilityis the command: it carries the listing, and itshandle()does the work. Everything about retries, uniqueness and overlap lives on the command itself.PushAvailability::dispatch()hands it to the bus. Whether it runs now (syncin tests) or on Redis in production is configuration, not code.- Because the command sends state instead of a change, running it twice is harmless, which is what makes coalescing and retries safe.
When not to use it
- Work the caller needs the result of right now (a price for the page) is a normal method call, not a queued command.
- Don’t queue tiny steps of one action separately; queue the action.
Laravel inside: the bus and the worker loop
dispatch() returns a PendingDispatch. When it goes out of scope, its destructor asks the unique lock first (that’s where coalescing happens), then hands the job to the bus.
// PendingDispatch
public function __destruct()
{
if (! $this->shouldDispatch()) { // ShouldBeUnique: Cache::lock(uniqueId)->get() failed
return; // dropped: a push for this listing is already waiting
}
app(Dispatcher::class)->dispatch($this->job);
}
// Dispatcher
public function dispatch($command)
{
return $this->queueResolver && $command instanceof ShouldQueue
? $this->dispatchToQueue($command) // serialize and push to Redis
: $this->dispatchNow($command); // call handle() now, with its dependencies injected
}
What a worker does, forever
public function daemon($connectionName, $queue, WorkerOptions $options)
{
while (true) {
if ($this->shouldQuit || $this->memoryExceeded($options->memory) || $this->queueShouldRestart($lastRestart)) {
$this->stop(); // queue:restart, or a memory limit: Supervisor starts a fresh one
}
$job = $this->getNextJob($connection, $queue); // Redis: move the job to a "reserved" set until retry_after
if ($job) {
$this->registerTimeoutHandler($job, $options); // pcntl alarm: kill the worker if the job passes its timeout
$this->runJob($job, $connectionName, $options); // handle(); then delete, release($delay), or fail
} else {
$this->sleep($options->sleep);
}
}
}
TestsA burst becomes one push, the runs are right, and the push sends them
<?php
use App\Channels\AvailabilityRuns;
use App\Channels\ChannelManager;
use App\Enums\Channel;
use App\Jobs\PushAvailability;
use App\Models\Booking;
use App\Models\ChannelConnection;
use App\Models\ChannelListing;
use App\Models\Property;
use Carbon\CarbonImmutable;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
beforeEach(function () {
$this->property = Property::factory()->create();
$this->listing = ChannelListing::forceCreate(['property_id' => $this->property->id, 'channel' => Channel::Airbnb, 'external_listing_id' => '41793625']);
});
it('queues one push for a burst of 200 changes', function () {
Queue::fake();
foreach (range(1, 200) as $change) {
PushAvailability::forProperty($this->property);
}
Queue::assertPushedTimes(PushAvailability::class, 1);
Queue::assertPushedOn('channels', PushAvailability::class);
});
it('groups the window into open and closed runs', function () {
Booking::factory()->for($this->property)->forStay('2027-06-03', 2)->create(); // closes 3 and 4 June
$runs = (new AvailabilityRuns())->for($this->property, CarbonImmutable::parse('2027-06-01'), 7);
expect(array_map(fn (array $run): array => [$run['nights']->checkIn->toDateString(), $run['nights']->nights(), $run['open']], $runs))->toBe([
['2027-06-01', 2, true],
['2027-06-03', 2, false],
['2027-06-05', 3, true],
]);
});
it('sends the whole calendar in one request and records the push', function () {
config(['services.airbnb' => ['base_url' => 'https://airbnb.test/v2', 'token_url' => 'https://airbnb.test/oauth/token', 'client_id' => 'id', 'client_secret' => 'secret', 'webhook_secret' => 's']]);
ChannelConnection::forceCreate(['account_id' => $this->property->account_id, 'channel' => Channel::Airbnb, 'access_token' => 'a', 'refresh_token' => 'r', 'expires_at' => now()->addHour()]);
Booking::factory()->for($this->property)->forStay('2027-06-03', 2)->create();
Http::fake(['airbnb.test/v2/*' => Http::response(['ok' => true])]);
app()->call([new PushAvailability($this->listing), 'handle']);
Http::assertSentCount(1); // one request per push, however many runs
Http::assertSent(fn (Request $request): bool => count($request['operations']) === 3
&& $request['operations'][1] === ['start_date' => '2027-06-03', 'end_date' => '2027-06-04', 'availability' => 'unavailable']);
expect($this->listing->fresh()->last_pushed_at)->not->toBeNull();
});
Queue::fake() keeps the unique lock: the job’s ShouldBeUnique check runs in PendingDispatch before any queue, real or fake, sees it.
Mutation: send one request per run again and assertSentCount(1) fails with 3.
The channel tests from scenes 14 and 16, on the new method
They called closeDates(), which no longer exists. Each now sends a small calendar instead:
21 unchanged lines
<?php use App\Bookings\Stay;use App\Channels\ChannelManager;use App\Channels\ChannelRequestFailed;use App\Enums\Channel;use App\Models\ChannelConnection;use App\Models\ChannelListing;use App\Models\Property;use Illuminate\Http\Client\Request;use Illuminate\Support\Facades\Http; beforeEach(function () { config([ 'services.airbnb' => ['base_url' => 'https://airbnb.test/v2', 'token_url' => 'https://airbnb.test/oauth/token', 'client_id' => 'id', 'client_secret' => 'secret'], 'services.booking_com' => ['base_url' => 'https://booking.test', 'username' => 'user', 'password' => 'pass'], ]); $this->property = Property::factory()->create(); $this->connection = ChannelConnection::forceCreate([ 'account_id' => $this->property->account_id, 'channel' => Channel::Airbnb, 'access_token' => 'old-access', 'refresh_token' => 'old-refresh', 'expires_at' => now()->addHour(), ]); $this->airbnb = ChannelListing::forceCreate(['property_id' => $this->property->id, 'channel' => Channel::Airbnb, 'external_listing_id' => '41793625']); $this->bookingCom = ChannelListing::forceCreate(['property_id' => $this->property->id, 'channel' => Channel::BookingCom, 'external_listing_id' => '1290031']); $this->nights = Stay::fromDates('2027-07-10', '2027-07-13'); $this->runs = [ ['nights' => Stay::fromDates('2027-07-10', '2027-07-13'), 'open' => false], ['nights' => Stay::fromDates('2027-07-13', '2027-07-20'), 'open' => true], ];}); it('closes nights on Airbnb as JSON, with the last night inclusive', function () {it('sends the calendar to Airbnb as JSON, with the last night inclusive', function () { Http::fake(['airbnb.test/*' => Http::response(['ok' => true])]); app(ChannelManager::class)->for(Channel::Airbnb)->api()->closeDates($this->airbnb, $this->nights); app(ChannelManager::class)->for(Channel::Airbnb)->api()->updateCalendar($this->airbnb, $this->runs); Http::assertSent(fn (Request $request): bool => $request->method() === 'PUT' && $request->url() === 'https://airbnb.test/v2/calendars/41793625' && $request->hasHeader('Authorization', 'Bearer old-access') && $request['end_date'] === '2027-07-12' && $request['availability'] === 'unavailable'); && $request['operations'] === [ ['start_date' => '2027-07-10', 'end_date' => '2027-07-12', 'availability' => 'unavailable'], ['start_date' => '2027-07-13', 'end_date' => '2027-07-19', 'availability' => 'available'], ]);}); it('closes nights on Booking.com as XML, and treats an error inside a 200 as a failure', function () {it('sends the calendar to Booking.com as XML, and treats an error inside a 200 as a failure', function () { Http::fake(['booking.test/*' => Http::response('<response><error code="401">Bad credentials</error></response>', 200)]); expect(fn () => app(ChannelManager::class)->for(Channel::BookingCom)->api()->closeDates($this->bookingCom, $this->nights)) expect(fn () => app(ChannelManager::class)->for(Channel::BookingCom)->api()->updateCalendar($this->bookingCom, $this->runs)) ->toThrow(ChannelRequestFailed::class, 'booking_com answered 200');}); it('refreshes an expiring token before calling, and stores the new pair', function () { $this->connection->update(['expires_at' => now()->addSeconds(30)]); Http::fake([ 'airbnb.test/oauth/token' => Http::response(['access_token' => 'new-access', 'refresh_token' => 'new-refresh', 'expires_in' => 3600]), 'airbnb.test/v2/*' => Http::response(['ok' => true]), ]); app(ChannelManager::class)->for(Channel::Airbnb)->api()->closeDates($this->airbnb, $this->nights); app(ChannelManager::class)->for(Channel::Airbnb)->api()->updateCalendar($this->airbnb, $this->runs); expect($this->connection->fresh()) ->access_token->toBe('new-access')7 unchanged lines
->refresh_token->toBe('new-refresh'); Http::assertSent(fn (Request $request): bool => $request->hasHeader('Authorization', 'Bearer new-access'));}); it('stores tokens encrypted', function () { expect($this->connection->getRawOriginal('access_token'))->not->toContain('old-access');});
15 unchanged lines
<?php use App\Bookings\Stay;use App\Channels\ChannelManager;use App\Channels\ChannelRateLimited;use App\Channels\ChannelRequestFailed;use App\Enums\Channel;use App\Models\ChannelConnection;use App\Models\ChannelListing;use App\Models\Property;use Carbon\CarbonImmutable;use Illuminate\Support\Facades\Http; beforeEach(function () { config(['services.airbnb' => ['base_url' => 'https://airbnb.test/v2', 'token_url' => 'https://airbnb.test/oauth/token', 'client_id' => 'id', 'client_secret' => 'secret', 'webhook_secret' => 's', 'requests_per_minute' => 300]]); $property = Property::factory()->create(); ChannelConnection::forceCreate(['account_id' => $property->account_id, 'channel' => Channel::Airbnb, 'access_token' => 'a', 'refresh_token' => 'r', 'expires_at' => now()->addHour()]); $this->listing = ChannelListing::forceCreate(['property_id' => $property->id, 'channel' => Channel::Airbnb, 'external_listing_id' => '41793625']); $this->close = fn () => app(ChannelManager::class)->for(Channel::Airbnb)->api()->closeDates($this->listing, Stay::fromDates('2027-07-10', '2027-07-13')); $this->close = fn () => app(ChannelManager::class)->for(Channel::Airbnb)->api()->updateCalendar($this->listing, [['nights' => Stay::fromDates('2027-07-10', '2027-07-13'), 'open' => false]]);}); it('retries a 503 and succeeds on the third attempt', function () {28 unchanged lines
Http::fake(['airbnb.test/v2/*' => Http::sequence()->push('Unavailable', 503)->push('Unavailable', 503)->push(['ok' => true])]); ($this->close)(); Http::assertSentCount(3);}); it('never retries a 429 or a 400', function (int $status, string $exception) { Http::fake(['airbnb.test/v2/*' => Http::response('No', $status, ['Retry-After' => '30'])]); expect($this->close)->toThrow($exception); Http::assertSentCount(1); // the incident: no burst of retries})->with([ 'rate limited' => [429, ChannelRateLimited::class], 'bad request' => [400, ChannelRequestFailed::class],]); it('reads Retry-After as seconds or as an HTTP date', function (string $header, int $seconds) { $this->travelTo(CarbonImmutable::parse('2027-06-01 10:00:00', 'UTC')); expect(ChannelRateLimited::fromRetryAfter('airbnb', $header)->retryAfter)->toBe($seconds);})->with([ 'seconds' => ['120', 120], 'a date' => ['Tue, 01 Jun 2027 10:02:30 GMT', 150], // the form that used to become 0 'a date in the past' => ['Tue, 01 Jun 2027 09:00:00 GMT', 1], 'missing' => ['', 60], 'unreadable' => ['soon', 60],]);
10 unchanged lines
<?php use App\Bookings\Stay;use App\Channels\ChannelApi;use App\Channels\ChannelRateLimited;use App\Channels\ThrottledChannelApi;use App\Models\ChannelListing;use Carbon\CarbonImmutable; it('stops calling at the limit and says how long to wait', function () { $inner = new class implements ChannelApi { public int $calls = 0; public function closeDates(ChannelListing $listing, Stay $nights): void public function updateCalendar(ChannelListing $listing, array $runs): void { $this->calls++; } public function openDates(ChannelListing $listing, Stay $nights): void { } public function reservationsUpdatedSince(ChannelListing $listing, CarbonImmutable $since): iterable { return []; } }; $api = new ThrottledChannelApi($inner, 'airbnb', perMinute: 2); $nights = Stay::fromDates('2027-07-10', '2027-07-13'); $api->closeDates(new ChannelListing(), $nights); $api->closeDates(new ChannelListing(), $nights); expect(fn () => $api->closeDates(new ChannelListing(), $nights))->toThrow(ChannelRateLimited::class) $runs = [['nights' => Stay::fromDates('2027-07-10', '2027-07-13'), 'open' => false]]; $api->updateCalendar(new ChannelListing(), $runs); $api->updateCalendar(new ChannelListing(), $runs); expect(fn () => $api->updateCalendar(new ChannelListing(), $runs))->toThrow(ChannelRateLimited::class) ->and($inner->calls)->toBe(2); // the third call never reached the channel});
The fake implements the new method; without it PHP would refuse to load the class, and the whole suite would stop.
Remember
- Push the current state in one request, not each change, and let a unique job coalesce a burst into one push.
- Slow outside work gets its own queue, so it never sits in front of guest emails.
Pushes are calm and correct. Tuesday night, a guest books the Lake Cabin on Airbnb while another books the same nights on Booking.com, 40 seconds apart.