DEV Community

Cover image for Sending a Birthday Message at 9 AM in Every Timezone with Laravel
Abiodun Paul Ogunnaike
Abiodun Paul Ogunnaike

Posted on

Sending a Birthday Message at 9 AM in Every Timezone with Laravel

The scheduling, idempotency and leap-year lessons I learned building CelebrateMe, a Laravel SaaS.
Sending a Birthday Message at 9 AM in Every Timezone with Laravel
When I started building CelebrateMe, my SaaS for celebrating the people who matter, the core feature sounded trivial: send the celebration message on the right day.

Then the first bug report came in. A user in Lagos got their message at 9 AM. A user in Los Angeles got theirs at 1 AM. A user in Sydney got theirs the day after the birthday.

"The right day" turns out to mean "the right day for the person receiving it". That one sentence reshaped the whole scheduling layer. Here's how I built it in Laravel, and the traps I fell into along the way.

The naive version (don't do this)
// routes/console.php
Schedule::command('celebrations:send')->dailyAt('09:00');
Celebration::whereMonth('date', now()->month)
->whereDay('date', now()->day)
->each(fn ($c) => $c->user->notify(new CelebrationNotification($c)));

This has three problems:

  1. 09:00 is server time. Everyone else gets it at a random hour.
  2. now() is the server's date. For half the planet it's already tomorrow, or still yesterday.
  3. If the scheduler misses that one run (a deploy, a crashed worker, a server reboot), nobody gets anything that day. There is no retry.

Step 1: Store the right data
Two changes to the data model:
• Every user gets an IANA timezone (Africa/Lagos, America/Los_Angeles). Never a raw offset like +01:00, because offsets change with daylight saving.
• A celebration stores month and day as separate integer columns. A birthday is a recurring calendar date, not a point in time.
Schema::create('celebrations', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->unsignedTinyInteger('month');
$table->unsignedTinyInteger('day');
$table->timestamp('paused_at')->nullable();
$table->timestamps();

$table->index(['month', 'day']);
Enter fullscreen mode Exit fullscreen mode

});

Validate the timezone when the user saves it:
'timezone' => ['required', 'timezone:all'],
Step 2: Run often, send in a local window
Instead of one daily run, the scheduler runs every 15 minutes. Fifteen, not sixty, because some timezones sit at half-hour and 45-minute offsets (India is UTC+5:30, Nepal is UTC+5:45).
// routes/console.php
Schedule::command('celebrations:dispatch')
->everyFifteenMinutes()
->withoutOverlapping()
->onOneServer();
onOneServer() matters as soon as you run more than one app server. Without it, every server dispatches the same messages. It needs a shared cache driver such as Redis or the database.
The command doesn't ask "is it 9 AM?" It asks "which timezones are currently inside the send window?":
class DispatchDueCelebrations extends Command
{
protected $signature = 'celebrations:dispatch';

private const WINDOW_START = 9;  // 09:00 local
private const WINDOW_END = 12;   // stop catching up at 12:00 local

public function handle(): int
{
    $nowUtc = now('UTC');

    $timezones = User::query()->distinct()->pluck('timezone');

    foreach ($timezones as $tz) {
        $local = $nowUtc->copy()->setTimezone($tz);

        if ($local->hour < self::WINDOW_START || $local->hour >= self::WINDOW_END) {
            continue;
        }

        $this->dueCelebrations($tz, $local)
            ->lazyById(500)
            ->each(fn (Celebration $c) => SendCelebrationMessage::dispatch($c, $local->year));
    }

    return self::SUCCESS;
}

private function dueCelebrations(string $tz, CarbonInterface $local): Builder
{
    return Celebration::query()
        ->whereNull('paused_at')
        ->whereHas('user', fn ($q) => $q->where('timezone', $tz))
        ->where('month', $local->month)
        ->where(function ($q) use ($local) {
            $q->where('day', $local->day);

            // Feb 29 birthdays get celebrated on Feb 28 in non-leap years
            if ($local->month === 2 && $local->day === 28 && ! $local->isLeapYear()) {
                $q->orWhere('day', 29);
            }
        });
}
Enter fullscreen mode Exit fullscreen mode

}
Notice the window is 9 AM to 12 PM, not "exactly 9:00". That's on purpose. If a deploy kills the 9:00 run, the 9:15 run picks those messages up. If the queue is down for two hours, the window still catches them.
But a three-hour window run every 15 minutes means the same celebration gets dispatched up to 12 times. That's the next problem.
Step 3: Make sending idempotent
The rule I now follow for every scheduled job: assume it will run more than once. Retries, overlapping runs, catch-up windows and manual re-runs all happen eventually.
A small deliveries table with a unique index is the source of truth:
Schema::create('celebration_deliveries', function (Blueprint $table) {
$table->id();
$table->foreignId('celebration_id')->constrained()->cascadeOnDelete();
$table->unsignedSmallInteger('year');
$table->string('status')->default('pending');
$table->timestamp('sent_at')->nullable();
$table->timestamps();

$table->unique(['celebration_id', 'year']);
Enter fullscreen mode Exit fullscreen mode

});
The job then has two layers of protection:
class SendCelebrationMessage implements ShouldQueue, ShouldBeUnique
{
use Queueable;

public int $tries = 3;
public array $backoff = [60, 300];

public function __construct(
    public Celebration $celebration,
    public int $year,
) {}

// Layer 1: don't even queue a duplicate while one is waiting
public function uniqueId(): string
{
    return "{$this->celebration->id}-{$this->year}";
}

public function handle(): void
{
    // Layer 2: the database decides, even across servers and retries
    $delivery = CelebrationDelivery::createOrFirst(
        ['celebration_id' => $this->celebration->id, 'year' => $this->year],
        ['status' => 'pending'],
    );

    if ($delivery->status === 'sent') {
        return;
    }

    $this->celebration->user->notify(
        new CelebrationNotification($this->celebration)
    );

    $delivery->update(['status' => 'sent', 'sent_at' => now()]);
}
Enter fullscreen mode Exit fullscreen mode

}
createOrFirst() (Laravel 10.20+) tries the insert first and falls back to a select if the unique index rejects it. That makes it safe under race conditions, unlike firstOrCreate().
The status only flips to sent after the notification succeeds. If the mail provider times out, the job retries and the row is still pending, so it tries again instead of silently skipping.
Step 4: Test it by time-travelling
Timezone code you haven't tested is broken. You just don't know where yet. Laravel's time helpers make this pleasant:
it('sends at 9am local time, not server time', function () {
Notification::fake();

$user = User::factory()->create(['timezone' => 'America/Los_Angeles']);
Celebration::factory()->for($user)->create(['month' => 11, 'day' => 27]);

// 09:00 in Lagos = 00:00 in LA → nothing should send
$this->travelTo(Carbon::parse('2026-11-27 09:00', 'Africa/Lagos'));
$this->artisan('celebrations:dispatch');
Notification::assertNothingSent();

// 09:00 in LA → send
$this->travelTo(Carbon::parse('2026-11-27 09:00', 'America/Los_Angeles'));
$this->artisan('celebrations:dispatch');
Notification::assertSentTo($user, CelebrationNotification::class);
Enter fullscreen mode Exit fullscreen mode

});

it('never sends twice in the same year', function () {
Notification::fake();

$user = User::factory()->create(['timezone' => 'Africa/Lagos']);
Celebration::factory()->for($user)->create(['month' => 11, 'day' => 27]);

foreach (['09:00', '09:15', '10:30', '11:45'] as $time) {
    $this->travelTo(Carbon::parse("2026-11-27 {$time}", 'Africa/Lagos'));
    $this->artisan('celebrations:dispatch');
}

Notification::assertSentToTimes($user, CelebrationNotification::class, 1);
Enter fullscreen mode Exit fullscreen mode

});
Add cases for a Feb 29 birthday in 2027, a user in Asia/Kathmandu, and the day daylight saving changes. Those are the ones that bite.
What I'd tell myself before starting
• Store intent, not instants. "Nov 27 in the user's timezone" is the fact. "2026-11-27 08:00 UTC" is something you calculate from it.
• Windows beat exact times. A scheduler that only fires once is a scheduler that will one day miss.
• Idempotency belongs in the database. Cache locks and unique jobs help, but a unique index is the thing that actually holds.
• Test with time travel. If your tests only run at the server's current time, they test almost nothing.
None of this is exotic. It's the plain, slightly boring reliability work that decides whether a product feels trustworthy. When someone sets up a celebration for their mum, it has to land on the right morning, every year.
If you're building something with scheduled, user-facing sends, I'd love to hear how you handled timezones. And if you want to see where this ends up, CelebrateMe is at [your CelebrateMe link].
I'm a backend engineer working with PHP and Laravel, and I also build custom WordPress themes and plugins. Find me on [https://linkedin.com/in/abiodun-paul-ogunnaike / https://github.com/abbeymaniak].

Top comments (2)

Collapse
 
mosmox_studio profile image
Mosmox Studio •

Did you consider storing a next_send_at in UTC on each celebration instead of looping over timezones? The dispatcher becomes one indexed where('next_send_at', '<=', now()) query and you recompute it after each delivery. The trade-off is that you have to recompute on every timezone change and handle the catch-up window yourself, so I can see why the 9–12 window approach wins on simplicity.

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

One catch in step 3. If CelebrationNotification implements ShouldQueue, notify() only pushes it onto the queue (NotificationSender::send checks that before anything else), so the row flips to sent before any mail goes out. A provider timeout then retries inside the notification job, and your pending-row retry never fires. Is yours sent sync?