Technology1 min read

Delete Expired Sessions in Laravel With a Scheduled Command

By · Published by Everything Blog

In short

The dedicated Artisan garbage-collection command allows teams to safely disable the default random lottery system that executes maintenance queries during incoming web requests. This background approach applies specifically to database and file drivers, since systems like Redis automatically expire entries using time-to-live settings. Users remain entirely blocked from accessing outdated sessions regardless of cleanup timing because the framework verifies session age upon every read.

Key points

  • Setting the session lottery configuration to zero removes resource-intensive cleanup rout…: Setting the session lottery configuration to zero removes resource-intensive cleanup routines from user-facing web requests.
  • Database session drivers require running the cleanup command on a single server, whereas…: Database session drivers require running the cleanup command on a single server, whereas local file setups must execute on every machine.
  • Cache-backed session stores like Redis and DynamoDB do not need this command because they…: Cache-backed session stores like Redis and DynamoDB do not need this command because they utilize automated time-to-live expiration.

Sources checked by our analysis pipeline: 1

If your Laravel app uses the database

or file

session driver, expired sessions stay in storage until Laravel deletes them. On Laravel 13.39 or later, you can delete them with the session:garbage-collect

Artisan command on a schedule:

// routes/console.phpuse Illuminate\Support\Facades\Schedule; Schedule::command('session:garbage-collect')->hourly();

The command runs the same cleanup Laravel already runs during some web requests. With the command on a schedule and the lottery turned off, no web request waits for the cleanup.

Note: The redis

, memcached

, dynamodb

, apc

, and cookie

drivers expire sessions without a cleanup step, so apps that use them don't need the command.

Turn Off the Session Lottery

Without a scheduled command, Laravel deletes expired sessions during web requests. The lottery

option in config/session.php

sets how often:

'lottery' => [2, 100],

The two numbers are odds. The default [2, 100]

gives each request that starts a session a 2 in 100 chance of running the cleanup. That request runs the delete before it reaches your route and waits for it to finish.

The odds stay the same whatever your traffic. At 1,000 requests…

Technology