It's 12:00 AM. Your cron job begins, like it does every night.
Except tonight, you have 40,000 active subscribers instead of 400.
The job begins charging every subscription that's due to expire that day, and in a few seconds, your database connections get maxed out. Stripe may begin returning 429 Too Many Requests errors. Then PHP times out. Now you don't know who actually got charged and who didn't.
This is the midnight cron nightmare. It's one of the most common yet avoidable flaws in subscription billing systems, and almost every self-built backend hits it at one point. Here's exactly why it happens, and how to build it correctly in Laravel 13.
The Straightforward Approach (And Why It Feels Fine at First)
Most subscription systems start out with something like this:
protected function schedule(Schedule $schedule): void
{
$schedule->call(function () {
Subscription::where('ends_at', '<=', now())
->where('status', 'active')
->get()
->each(function (Subscription $subscription) {
$this->chargeSubscription($subscription);
});
})->dailyAt('00:00');
}
It's very simple, readable, and works perfectly fine in local dev with 10 test subscriptions. It'll probably survive your first few hundred users too. But this approach doesn't fail because it's wrong on day one. It fails because it's a ticking clock tied directly to your growth curve.
Why This Breaks at Scale
There are four massive issues hiding behind that simple loop:
1. The Chokepoint
If every subscription is set to renew "at expiration," and most of your users signed up around the same time (which happens naturally with growth spikes, promotions, or seasonal signups), you get a massive cluster of renewals landing on the exact same timestamp. This creates one enormous batch with zero distribution.
2. Synchronous Charging Inside a Loop
Calling a payment API synchronously inside a foreach, inside a scheduled command, means your total runtime is (number of subscriptions) × (Stripe API latency). At 40,000 subscriptions and ~300ms per charge, that's over three hours in a single PHP process. That process holds a database connection open the whole time, has a max_execution_time limit, and has no way to resume if it crashes.
3. Stripe (and your database) Will Rate-Limit You
Payment providers cap requests per second for a reason. Hit the API synchronously from one process and you'll get throttled. Throttled requests with no backoff just fail. And if you retry without idempotency, those failures can turn into duplicate charges.
4. No Idempotency = No Safety Net
If the job crashes at subscription #22,000 and you simply re-run it, you now risk re-charging the first 22,000 users who already succeeded. If you aren't tracking which renewals already ran, every retry risks double-charging your users.
None of these are edge cases. They're the default behavior of the naive cron approach once you cross a few thousand active subscriptions.
The Professional Fix: Space-out, Queue, and Track
The fix isn't a bigger server or a longer timeout. It's rethinking three things: when renewals happen, how they're executed, and what proof you keep that they happened. Here's the shape of it end to end:
1. Stagger Billing Windows — Don't Renew Everyone at Once
Instead of one giant midnight batch, spread renewal attempts across a window, and separate the renewal attempt from the actual expiration:
// Two distinct timestamps instead of one
renewal_due_at // when we should attempt a renew
ends_at // when access actually ends if renewal fails
Attempting renewal a day or two before ends_at rather than exactly at expiration gives you room to retry failed charges, notify the user, and smoothly kill access if the payment fails, without giving away free unpaid access or charging everyone at the same time.
2. Never Charge Synchronously Inside the Scheduler
The scheduler's only job should be to find who needs billing and dispatch work — not to do the billing itself:
protected function schedule(Schedule $schedule): void
{
$schedule->call(function () {
Subscription::query()
->where('renewal_due_at', '<=', now())
->where('auto_renew', true)
->chunkById(200, function ($subscriptions) {
foreach ($subscriptions as $subscription) {
ProcessRenewal::dispatch($subscription);
}
});
})->dailyAt("00:00");
}
Two important changes here:
-
chunkById()instead ofget()— you never load 40,000 Eloquent models into memory at once. - Dispatch a queued job per subscription instead of charging inline — the scheduler's job finishes in milliseconds. The actual charging happens in the queue, where Laravel's worker pool naturally throttles concurrency, retries failed jobs, and won't take your whole app down if one charge hangs.
Notice there's no ->onQueue('billing') at the call site. Laravel 13 added Queue::route(), which lets you define the queue and connection in one place instead of repeating it every time you dispatch a job:
Queue::route(ProcessRenewal::class, connection: 'redis', queue: 'billing');
Running php artisan queue:work with a sane --tries and backoff strategy turns "one giant fragile loop" into "many small, retryable, independently-failing units of work", which is the more reliable and stable approach.
3. Make Every Renewal Attempt Idempotent
This is the piece most naive implementations skip entirely, and it's the one that actually saves you from double-charging customers on retry:
class ProcessRenewal implements ShouldQueue
{
public function handle(): void
{
// Bail if this cycle already resolved — either the renewal
// already succeeded (renewal_due_at moved forward) or it
// already failed (auto_renew got turned off).
if (!$this->subscription->auto_renew || $this->subscription->renewal_due_at->isFuture()) {
return;
}
$result = $this->chargeCustomer($this->subscription);
if ($result->successful()) {
$this->subscription->update([
'renewal_due_at' => now()->addMonth(),
'ends_at' => now()->addMonth(),
]);
} else {
$this->subscription->update(['auto_renew' => false]);
Mail::to($this->subscription->user)->queue(new RenewalFailed($this->subscription));
}
}
}
This checks real state, not a timestamp: if the renewal succeeded, renewal_due_at is already in the future. If it failed, auto_renew is already off. Either way, the job bails. If neither happened yet, it means the last attempt didn't reach an outcome, so a retry from Laravel's --tries/backoff mechanism can still fire and actually try the charge again. Pair this with treating the webhook as the real source of truth for a successful charge, and you've closed off the two biggest sources of billing bugs: duplicate charges and false-positive activations.
4. Keep Payment History, Don't Overwrite State
One more habit worth adopting: never delete or overwrite a payment record. Every attempt (successful, failed, or pending) should be its own row. When a customer emails asking "why was I charged twice" or "why did my renewal fail," you want a full audit trail, not a single status column that only remembers the most recent outcome.
Putting It Together
The shift is simple to state and easy to underestimate: stop treating billing as a loop, and start treating it as a distributed, idempotent, queue-driven sequence.
- Stagger renewal windows so you're not billing everyone at once
- Let the scheduler dispatch, not execute
- Queue the actual charge with retries and backoff
- Track idempotency so retries are always safe
- Trust webhooks over synchronous responses
- Keep full payment history for every attempt
None of this is exotic. Separating scheduling from doing, and attempting from confirming. But it's the difference between a billing system that quietly scales past 40,000 users and one that wakes you up at 3 AM.
A Reference Implementation
I ended up building this system in an open-source Laravel 13 backend called SubEngine — a webhook-driven subscription billing engine that implements strategic renewal timing, idempotent scheduler jobs, Stripe webhook verification, and full payment history preservation, with 31 passing tests covering the lifecycle end to end.
It's lightweight, focused on the backend billing logic that tends to break in the real world. If you're building (or rebuilding) subscription billing in Laravel, it's worth a look as a reference or a starting template.
If this saved you from a future midnight crash, a star on the repo goes a long way.