An expired TLS certificate is a full-site outage: browsers block visitors before your app runs. Calendar reminders and registrar emails slip. Laravel SSL certificate expiry monitoring with a scheduled job and queue reads the live certificate from port 443, stores not_after, and marks domains as expiring before the hard deadline.
This guide walks the loop used in production monitors: Laravel’s scheduler queues due domains, a queue worker runs CheckDomainJob, DomainChecker calls TlsProbe, and the domains table gets ssl_expires_at, status, and next_check_at for the next run. Alerts and RDAP domain expiry layer on top (covered in later posts in this series).
What you are building
cron (every minute) → php artisan schedule:run
→ monitors:check (hourly)
→ CheckDomainJob per due domain
→ DomainChecker::run()
→ TlsProbe::probe()
→ DomainCheck row + domain summary update
Manual Check now in the dashboard dispatches the same job immediately. Scheduled runs respect next_check_at and plan-based intervals.
Prerequisites
Laravel 11+ (scheduler in
routes/console.php).Queue driver
databaseorredisin production (QUEUE_CONNECTION).PHP OpenSSL enabled (
stream_socket_clientTLS).Optional: Supervisor for
queue:workand cron forschedule:run.
Why live TLS beats expiry spreadsheets
Panel dashboards show orders, not what strangers’ browsers see during handshake. A cert can be replaced early on the server while marketing still lists an old date, or a wildcard can expire while a leaf cert was renewed on another machine. Probing what the host presents on 443 is the operational truth. Registrar RDAP (later in this series) catches domain loss even when TLS is fine.
Step 1: Model monitored domains
Each row tracks hostname, port (usually 443), summary status, and scheduling fields:
// app/Models/Domain.php (excerpt)
public const STATUS_OK = 'ok';
public const STATUS_EXPIRING = 'expiring';
public const STATUS_EXPIRED = 'expired';
public const STATUS_UNREACHABLE = 'unreachable';
protected function casts(): array
{
return [
'ssl_expires_at' => 'datetime',
'last_checked_at' => 'datetime',
'next_check_at' => 'datetime',
'paused_at' => 'datetime',
];
}
public function isPaused(): bool
{
return $this->paused_at !== null;
}
next_check_at: the scheduler command only queues domains where next_check_at <= now() or null. After a successful check, bump next_check_at by check_interval_hours (free vs paid tiers can differ).
paused_at: skip monitoring without deleting history.
Migration sketch
Schema::create('domains', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('hostname');
$table->unsignedSmallInteger('port')->default(443);
$table->string('label')->nullable();
$table->string('status')->default('pending');
$table->timestamp('ssl_expires_at')->nullable();
$table->timestamp('registrar_expires_at')->nullable();
$table->timestamp('last_checked_at')->nullable();
$table->timestamp('next_check_at')->nullable();
$table->timestamp('paused_at')->nullable();
$table->unsignedSmallInteger('check_interval_hours')->default(24);
$table->timestamps();
$table->unique(['user_id', 'hostname', 'port']);
});
Schema::create('domain_checks', function (Blueprint $table) {
$table->id();
$table->foreignId('domain_id')->constrained()->cascadeOnDelete();
$table->timestamp('ran_at');
$table->boolean('tls_ok')->default(false);
$table->timestamp('cert_not_after')->nullable();
$table->json('raw')->nullable();
$table->timestamps();
});
History rows power sparklines and incident review (“was Tuesday’s failure DNS or cert?”).
Step 2: Schedule monitors:check
In routes/console.php:
use Illuminate\Support\Facades\Schedule;
Schedule::command('monitors:check')
->hourly()
->withoutOverlapping(55)
->onOneServer();
The command does not probe inline. It queues jobs for domains that are due:
// app/Console/Commands/CheckMonitors.php (excerpt)
$query = Domain::query()->whereNull('paused_at');
if (! $this->option('force')) {
$query->where(function ($due) {
$due->whereNull('next_check_at')
->orWhere('next_check_at', '<=', now());
});
}
$query->chunkById(200, function ($domains) use (&$queued) {
foreach ($domains as $domain) {
CheckDomainJob::dispatch($domain->id);
$queued++;
}
});
Cron on the server: Laravel expects * * * * * php /path/to/artisan schedule:run. The scheduler then decides hourly vs other intervals.
--force: queue every active domain (useful after deploy or incident). --domain=ID: single domain.
Verify scheduling locally
php artisan schedule:list
php artisan schedule:test
After adding a domain in tinker with next_check_at in the past:
php artisan monitors:check
php artisan queue:work --once
You should see a new domain_checks row and updated ssl_expires_at.
onOneServer() and locks
->onOneServer() avoids duplicate scheduler runs when multiple app servers share one cron. It requires a cache driver that supports atomic locks (Redis, database, Memcached), not file on multi-node deploys.
Step 3: Queue job with uniqueness
SSL checks can be slow (timeouts, RDAP). Run them on the queue, not in the HTTP request.
// app/Jobs/CheckDomainJob.php
class CheckDomainJob implements ShouldBeUnique, ShouldQueue
{
public int $tries = 2;
public int $timeout = 90;
public int $uniqueFor = 600;
public function __construct(public readonly int $domainId) {}
public function uniqueId(): string
{
return (string) $this->domainId;
}
public function handle(DomainChecker $checker, AlertEvaluator $alerts): void
{
$domain = Domain::with('user')->find($this->domainId);
if ($domain === null || $domain->isPaused()) {
return;
}
$previousStatus = $domain->status;
$check = $checker->run($domain);
$alerts->evaluate($domain->refresh(), $check, $previousStatus);
}
}
ShouldBeUnique prevents stacking ten jobs for example.com while a check is already queued. Tune uniqueFor to your worst-case probe duration.
Run workers:
php artisan queue:work --queue=default --sleep=3 --tries=2
Use Supervisor in production (see deploy post in this series).
Step 4: Run the probe and persist results
DomainChecker merges TLS (and RDAP in full kit) into a snapshot, writes a domain_checks history row, and updates the parent domain:
// app/Services/DomainChecker.php (excerpt)
public function run(Domain $domain): DomainCheck
{
$snapshot = $this->snapshot($domain->hostname, $domain->port);
$now = CarbonImmutable::now();
$check = $domain->checks()->create(array_merge($snapshot, ['ran_at' => $now]));
$domain->forceFill([
'status' => $this->statusFor($snapshot),
'ssl_expires_at' => $snapshot['cert_not_after'] ?? null,
'last_checked_at' => $now,
'next_check_at' => $now->addHours($this->plans->checkIntervalHours($domain->user)),
])->save();
return $check;
}
statusFor: maps probe output to human-facing state. Certificate within config('ssldays.expiring_days') (default 30) becomes expiring:
if ($snapshot['cert_not_after'] !== null) {
$days = now()->startOfDay()->diffInDays(
CarbonImmutable::parse($snapshot['cert_not_after'])->startOfDay(),
false,
);
if ($days <= config('ssldays.expiring_days')) {
return Domain::STATUS_EXPIRING;
}
}
.env:
SSLDAYS_EXPIRING_DAYS=30
SSLDAYS_PROBE_TIMEOUT=10
The probe itself (TlsProbe) opens TLS with SNI, reads the presented certificate, and parses validTo via openssl_x509_parse. A follow-up article in this series covers stream_socket_client details (php-stream-socket-client-ssl-certificate-expiry).
Step 5: Wire dashboard “Check now”
Users expect instant feedback when adding a domain. Dispatch the same job:
// app/Http/Controllers/DomainController.php (pattern)
public function checkNow(Domain $domain)
{
$this->authorize('update', $domain);
CheckDomainJob::dispatch($domain->id);
return back()->with('status', 'check-queued');
}
Do not call DomainChecker::run() synchronously on the web request unless you enforce short timeouts and accept user-visible latency.
Step 6: Operate in production
Process Purpose schedule:run via cron Fires monitors:check on cadence queue:work Executes CheckDomainJob php artisan monitors:check Manual operator queue php artisan ssldays:doctor Health check CA bundle, queue, cron (in kit)
If QUEUE_CONNECTION=database but no worker runs, jobs pile up and scheduled monitoring appears frozen. Add domain still queues one job via “Check now,” which confuses debugging.
Database queue vs Redis
QUEUE_CONNECTION=database is enough for hundreds of domains with a single worker. Redis shines when probes back up during incidents and you want multiple workers with visibility in Horizon. Neither replaces cron: schedule:run only enqueues; workers execute.
Retries and poison messages
$tries = 2 on CheckDomainJob limits hammering dead hosts. Failed jobs land in failed_jobs for inspection. A permanently broken hostname should flip to unreachable quickly without infinite retry loops poisoning the queue.
After checks: alerts (preview)
AlertEvaluator compares new status to the previous status and notify windows (notify_days on the domain model). Email and webhooks fire when a domain crosses into expiring or expired. That layer is separate from scheduling so you can change alert channels without touching monitors:check.
Step 7: Failure modes and status values
Status Meaning ok Cert valid, outside expiring window expiring Within SSLDAYS_EXPIRING_DAYS expired cert_not_after in the past unreachable TCP/TLS handshake failed untrusted Chain failed strict verification
Transient DNS blips should not permanently flip to expired. History in domain_checks helps support see flaky vs real expiry.
Step 8: Plan limits and fair scheduling
Multi-tenant monitors cap domains per account and refresh interval per plan tier. After each check, next_check_at should use PlanLimits::checkIntervalHours($user) so free accounts do not enqueue hourly jobs they will not run. The scheduler remains hourly globally; per-row next_check_at is the gate.
When a user imports a large list, chunkById in CheckMonitors prevents loading tens of thousands of Eloquent models in one PHP request. Watch queue depth during imports and temporarily raise worker count.
Step 9: Timezone and “days remaining” display
Store absolute ssl_expires_at from the probe. Compute “days remaining” in the UI with one consistent timezone policy (UTC start-of-day is common). Mixing user local midnight with server UTC causes off-by-one alert noise at month boundaries.
Step 10: Security and abuse
Scheduled jobs must use the same hostname and IP validation as interactive checks. Never probe arbitrary ports from user input; an allowlist (443 only by default) keeps the product from becoming a network scanner. Paused domains should short-circuit in the job before opening sockets.
Step 11: Capacity planning
Assume several seconds per check when RDAP is enabled. One queue worker processing one job every five seconds supports roughly twelve checks per minute. Scale workers with (domains due per hour × average duration) / 3600. Alert on queue latency, not just HTTP errors.
Step 12: Local development workflow
Use php artisan schedule:work and queue:work on laptops without system cron. Seed a domain with next_check_at = now()->subMinute(), run monitors:check, then queue:work --once to validate the loop before shipping Docker images.
Step 13: Bridge to the rest of the series
Article 02 explains PHP TLS reads in depth. Article 03 focuses on cron and Supervisor. Article 06 covers alert channels when status flips to expiring. Together they mirror what SSL Days wires in one codebase.
Troubleshooting
Scheduler runs but nothing checks
Confirm next_check_at is in the past and paused_at is null. Confirm queue worker is running.
All domains unknown or chain errors
Set SSLDAYS_CA_BUNDLE or php.ini openssl.cafile. Run doctor command after deploy.
Duplicate jobs
Ensure ShouldBeUnique on CheckDomainJob and avoid dispatching from both scheduler and user double-clicks without uniqueness.
Hourly schedule vs per-domain interval
The scheduler runs hourly; each domain’s check_interval_hours decides whether it is due. Free daily / paid hourly is a product rule, not a second cron entry.
Monitoring loop in the kit
SSL Days from Skryptix includes:
monitors:check,CheckDomainJob,TlsProbe, RDAP lookupDashboard status, pause/resume, alerts
Stripe billing, installer, public checker
FAQ
How do I monitor SSL certificate expiry in Laravel?
Store domains in the database, schedule monitors:check, queue CheckDomainJob per due domain, probe TLS for cert_not_after, and set ssl_expires_at plus next_check_at.
Do I need a queue worker for SSL monitoring?
Yes for production when checks run in queued jobs. Without queue:work, scheduled checks stay queued in the jobs table.
What cron entry does Laravel scheduling need?
* * * * * cd /path-to-app && php artisan schedule:run >> /dev/null 2>&1 so hourly commands like monitors:check actually fire.
How is expiring different from expired?
Expiring means the certificate is still valid but within your warning window (SSLDAYS_EXPIRING_DAYS). Expired means not_after is in the past.
Can I check SSL on demand as well as on a schedule?
Yes. Dispatch the same CheckDomainJob from a controller action; the scheduler handles recurring next_check_at.
Why use jobs instead of running probes in the scheduler command?
Probes can take seconds each and block the scheduler process. Queued jobs parallelize across workers and respect timeouts/retries.
What PHP API reads the certificate expiry date?
stream_socket_client to ssl://host:443 with SNI, then openssl_x509_parse on the peer certificate (covered in depth in article 02 of this series).
Should I use Laravel Horizon for SSL monitoring queues?
Horizon is optional but helpful when you run many workers. Database queues work fine at small scale. Horizon adds dashboards for throughput and failure rates when SSL checks spike during mass renewals.
How do I pause monitoring during maintenance?
Set paused_at on the domain row before intentional cert replacement. Resume after validating the new leaf on prod. The scheduler skips paused rows until you clear the timestamp.
What happens if cron stops but workers keep running?
Queued jobs still drain, but monitors:check never fires, so next_check_at stops advancing for the fleet. Page both scheduler and worker health. SSL monitors fail quietly when cron dies.
Field notes from operating monitors
Teams often discover that calendar reminders and monitoring disagree because someone renewed on a load balancer but not on the origin that still serves legacy traffic. Live TLS probes reduce that split-brain story.
Another common surprise: auto-renewing CAs still fail when DNS or HTTP challenge paths break. Your status may show expiring close to deadline even though the vendor “should” renew. Alerts give you time to fix ACME before browsers fail.
Finally, schedule and queue health are invisible to customers until everything is red. Put cron and worker checks in your own internal uptime dashboard. SSL monitoring products must monitor themselves.
New domain onboarding path
When a customer adds api.customer.com, create the row with status = pending and dispatch a job immediately. Set nex
