Course › Day 4 · Hosts and guests › Scene 22 of 49 · 20 min
Guest got the door code twice
An atomic pending → sent claim; a BookingCancelled event with independent listeners
On this page
#supportThursday 15:02
Mona · supportThe Nyhavn guest got “Your door code is 4711” twice, at 15:00:58 and 15:01:02.
The broken code
public function handle(): void
{
Notification::route('mail', $booking->guest_email)->notifyNow(new GuestMessage($this->message)); // 1. send
$this->message->forceFill(['status' => ScheduledMessageStatus::Sent, 'sent_at' => now()])->save(); // 2. then mark
}
At 15:00 the scheduler queued the message. The workers were busy, so at 15:01 it was still pending, and the scheduler queued it again. Two jobs, two workers, both sent before either marked it. The same happens when a job sends the email and then crashes before step 2: the retry sends it again.
How the fix works, in one picture
Before
Two workers both saw the message as pending and both sent it.
After
Sending starts with one conditional update; only the worker that changed the row sends.
The fix: claim the message before sending it
The status check and the status change have to be one step, or two workers can both see "pending". A conditional UPDATE ... WHERE status = 'pending' is exactly that: the database runs it atomically, so for one message only one worker can ever change the row. update() returns how many rows changed: 1 means "it’s yours, send it", 0 means someone else already did, or it was cancelled.
7 unchanged lines
<?php namespace App\Jobs; use App\Enums\ScheduledMessageStatus;use App\Models\ScheduledMessage;use App\Notifications\GuestMessage;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Support\Facades\Notification;use Throwable; class SendScheduledMessage implements ShouldQueue{7 unchanged lines
use Queueable; public int $tries = 3; public function __construct(public ScheduledMessage $message) { } public function handle(): void { $booking = $this->message->booking; Notification::route('mail', $booking->guest_email)->notifyNow(new GuestMessage($this->message)); $this->message->forceFill(['status' => ScheduledMessageStatus::Sent, 'sent_at' => now()])->save(); $claimed = ScheduledMessage::query() ->whereKey($this->message->id) ->where('status', ScheduledMessageStatus::Pending) // only if nobody got here first ->update(['status' => ScheduledMessageStatus::Sent, 'sent_at' => now()]); if ($claimed === 0) { return; // already sent, or cancelled } try { Notification::route('mail', $this->message->booking->guest_email)->notifyNow(new GuestMessage($this->message)); } catch (Throwable $e) { ScheduledMessage::query()->whereKey($this->message->id)->update(['status' => ScheduledMessageStatus::Pending, 'sent_at' => null]); throw $e; // give it back, so the retry can claim it } }}
The order is a deliberate choice. Marking before sending means a crash between the two can lose a message (at most once). Marking after means a crash can send it twice (at least once). For a door code, a missing message is noticed and resent by support; a duplicate can’t be taken back. The catch covers the common failure, a mail server error, by giving the message back.
TestsTwo jobs send once, and a failed send can be retried
<?php
use App\Enums\ScheduledMessageStatus;
use App\Jobs\SendScheduledMessage;
use App\Models\Booking;
use App\Models\MessageTemplate;
use App\Models\ScheduledMessage;
use App\Notifications\GuestMessage;
use Illuminate\Contracts\Notifications\Dispatcher;
use Illuminate\Support\Facades\Notification;
function scheduled(Booking $booking, string $name, ScheduledMessageStatus $status = ScheduledMessageStatus::Pending): ScheduledMessage
{
$template = MessageTemplate::forceCreate(['account_id' => $booking->property->account_id, 'name' => $name, 'trigger' => 'before_check_in', 'days_offset' => -1, 'send_time' => '15:00', 'subject' => $name, 'body' => 'Door code: {door_code}']);
return ScheduledMessage::forceCreate(['booking_id' => $booking->id, 'message_template_id' => $template->id, 'send_at' => now()->subMinute(), 'status' => $status]);
}
it('sends once when two jobs run for the same message', function () {
Notification::fake();
$message = scheduled(Booking::factory()->create(), 'Arrival');
app()->call([new SendScheduledMessage($message), 'handle']);
app()->call([new SendScheduledMessage($message), 'handle']); // the scheduler queued it again
Notification::assertSentOnDemandTimes(GuestMessage::class, 1);
});
it('gives the message back when sending fails, so the retry can send it', function () {
$this->mock(Dispatcher::class)->shouldReceive('sendNow')->once()->andThrow(new RuntimeException('SMTP timeout'));
$message = scheduled(Booking::factory()->create(), 'Arrival');
expect(fn () => app()->call([new SendScheduledMessage($message), 'handle']))->toThrow(RuntimeException::class)
->and($message->fresh()->status)->toBe(ScheduledMessageStatus::Pending);
});
Follow-up, the same afternoon: a cancelled guest gets the key box code
While Karim was deploying the claim, Mona brought the second message from the same afternoon.
#supportThursday 16:20
Mona · supportA guest who cancelled last week just got arrival instructions for the Lake Cabin, with the key box code. The host is not happy.
Karim · developerCancelling a booking (scene 10) never touches its messages. They stay pending and go out on time, to a guest who isn’t coming.
How the fix works, in one picture
Before
Cancelling never touched the booking’s messages.
After
The cancellation is an event; each consequence is its own listener.
The fix: a cancellation announces itself
Cancelling a booking now needs to cancel its messages, email the guest a confirmation, and soon more (Day 5 cancels the cleaning task). Putting each of those calls into CancelBooking makes it know about messaging, email and cleaning. Instead, it announces one fact, "this booking was cancelled", and every part of the app that cares listens.
The event
ShouldDispatchAfterCommit: the event is held until the transaction in CancelBooking commits. If the cancellation rolls back, nobody hears about it.
<?php
namespace App\Events;
use App\Models\Booking;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class BookingCancelled implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(public Booking $booking)
{
}
}
CancelBooking (scene 10) dispatches it right after the state changed:
<?php namespace App\Bookings; use App\Channels\CalendarSync;use App\Enums\PaymentStatus;use App\Events\BookingCancelled;use App\Jobs\RefundCancelledBooking;use App\Models\Booking;use App\Money\Money;17 unchanged lines
use Illuminate\Support\Facades\DB; final class CancelBooking{ public function __construct(private CalendarSync $calendar) { } /** @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; } $this->calendar->bookingChanged($booking); // the nights are free again BookingCancelled::dispatch($booking); // anyone who cares listens; held until the commit $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; }); }}
A booking cancelled on Airbnb or Booking.com arrives through the import (scene 15). It dispatches the same event the first time it sees the cancellation, so those messages stop too:
<?php namespace App\Channels; use App\Enums\BookingStatus;use App\Events\BookingCancelled;use App\Messaging\ScheduleGuestMessages;use App\Models\Booking;use App\Models\ChannelListing;29 unchanged lines
use App\Models\Property;use Illuminate\Support\Facades\DB; final class ImportChannelReservation{ public function __construct( private CalendarSync $calendar, private ScheduleGuestMessages $scheduleMessages, ) { } /** @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 } $wasCancelled = $booking->status === BookingStatus::Cancelled; $booking->forceFill([ 'property_id' => $listing->property_id, 'channel' => $reservation->channel,15 unchanged lines
'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(); $this->calendar->bookingChanged($booking); // clashes are found here, and the channels told if ($booking->status === BookingStatus::Confirmed) { $this->scheduleMessages->handle($booking); // the same messages as a booking made on our site } if ($booking->status === BookingStatus::Cancelled && ! $wasCancelled) { BookingCancelled::dispatch($booking); // cancelled on the channel: the same event as ours } return true; }); }}
Listener 1: stop the messages
Only pending rows change; a message already sent stays in the history as sent.
<?php
namespace App\Listeners;
use App\Enums\ScheduledMessageStatus;
use App\Events\BookingCancelled;
class CancelScheduledMessages
{
public function handle(BookingCancelled $event): void
{
$event->booking->scheduledMessages()
->where('status', ScheduledMessageStatus::Pending)
->update(['status' => ScheduledMessageStatus::Cancelled]);
}
}
It runs right away, not on a queue: a message due in the next minute must be stopped before the scheduler finds it. And because the claim above only takes pending rows, a send job already queued for it now finds nothing to claim.
Listener 2: tell the guest
ShouldQueue: email is slow and can fail, so this one runs on the queue, with its own retries, and never delays the cancellation.
<?php
namespace App\Listeners;
use App\Events\BookingCancelled;
use App\Notifications\BookingCancelledNotice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Notification;
class SendCancellationConfirmation implements ShouldQueue
{
public int $tries = 3;
public function handle(BookingCancelled $event): void
{
Notification::route('mail', $event->booking->guest_email)->notify(new BookingCancelledNotice($event->booking));
}
}
Nothing registers these listeners: Laravel discovers every class in app/Listeners and reads the event from the type of handle()’s parameter. php artisan event:list shows the result.
<?php
namespace App\Notifications;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class BookingCancelledNotice extends Notification
{
use Queueable;
public function __construct(public Booking $booking)
{
}
/** @return list<string> */
public function via(object $notifiable): array
{
return ['mail'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage())
->subject("Your stay at {$this->booking->property->name} is cancelled")
->line("Your booking from {$this->booking->stay->checkIn->toFormattedDateString()} has been cancelled.");
}
}
You just met Observer and Event Dispatcher
ObserverAn object announces that something happened, and any number of other objects react, without the announcer knowing who they are.
Event DispatcherOne central object that carries events from whoever dispatches them to every listener registered for them. Laravel’s Event facade.
CancelBookingknows one thing: a booking was cancelled. Adding a reaction (cancel the cleaning task, update a report) is a new listener, andCancelBookingnever changes.- Each listener chooses how it runs: right away (stop the messages before the next minute) or queued (the email).
- Compare scene 18’s mediator: the calendar needs one place that decides the order (find clashes, then push), so it stays a mediator. Reactions that are independent of each other are better as listeners.
When not to use it
- When the caller needs the result, or the steps must happen in a fixed order, call them directly. Events hide the flow: reading
CancelBookingno longer tells you everything that happens. - Don’t use events to pass data back to the dispatcher. A listener that must succeed for the action to make sense is a step, not a listener.
Laravel inside: dispatching an event
The dispatcher looks up the listeners for the event’s class and calls each in turn. A listener that implements ShouldQueue isn’t called: it is wrapped in a CallQueuedListener job and pushed to the queue instead.
public function dispatch($event, $payload = [], $halt = false)
{
if ($event instanceof ShouldDispatchAfterCommit && $this->transactionManager?->getPendingTransactions()->isNotEmpty()) {
$this->transactionManager->addCallback(fn () => $this->invokeListeners($event, $payload, $halt)); // after COMMIT
return null;
}
return $this->invokeListeners($event, $payload, $halt);
}
protected function invokeListeners($event, $payload, $halt = false)
{
foreach ($this->getListeners(get_class($event)) as $listener) { // queued listeners are wrapped here: CallQueuedListener
$response = $listener($event, $payload);
if ($response === false) {
break; // a listener can stop the rest by returning false
}
}
}
TestsA cancellation stops what is pending, keeps what was sent, and is announced once
<?php
use App\Bookings\CancelBooking;
use App\Enums\ScheduledMessageStatus;
use App\Events\BookingCancelled;
use App\Models\Booking;
use App\Models\MessageTemplate;
use App\Models\ScheduledMessage;
use Illuminate\Support\Facades\Event;
function message(Booking $booking, string $name, ScheduledMessageStatus $status): ScheduledMessage
{
$template = MessageTemplate::forceCreate(['account_id' => $booking->property->account_id, 'name' => $name, 'trigger' => 'before_check_in', 'days_offset' => -1, 'send_time' => '15:00', 'subject' => $name, 'body' => 'Door code: {door_code}']);
return ScheduledMessage::forceCreate(['booking_id' => $booking->id, 'message_template_id' => $template->id, 'send_at' => now()->subMinute(), 'status' => $status]);
}
it('cancels pending messages when the booking is cancelled, and keeps the sent ones', function () {
$booking = Booking::factory()->create();
$pending = message($booking, 'Arrival', ScheduledMessageStatus::Pending);
$sent = message($booking, 'Thanks', ScheduledMessageStatus::Sent);
app(CancelBooking::class)->handle($booking);
expect($pending->fresh()->status)->toBe(ScheduledMessageStatus::Cancelled)
->and($sent->fresh()->status)->toBe(ScheduledMessageStatus::Sent);
});
it('announces the cancellation once', function () {
Event::fake([BookingCancelled::class]);
$booking = Booking::factory()->create();
app(CancelBooking::class)->handle($booking);
app(CancelBooking::class)->handle($booking); // already cancelled: no second event
Event::assertDispatchedTimes(BookingCancelled::class, 1);
});
Remember
- "Send once" is an atomic claim: one
UPDATE … WHERE status = pending, and only the winner sends. - Cancelling a booking is an event; each consequence is its own listener.
Messages go out once, and stop when a booking does. Friday: a guest extends her stay by two nights, the extra charge fails, and the booking is left half changed.