LifterLMS Database Optimization: Safe Cleanup for Faster Course Sites

Which LifterLMS tables grow, which rows are safe to remove and which never are, how to measure table sizes, a batched pruning script for old events and notifications, and the WordPress-level cleanup that matters on course sites.

  • Add as a preferred source on Google
Illustration for “LifterLMS Database Optimization: Safe Cleanup for Faster Course Sites”

A LifterLMS site's database grows every time a student logs in, opens a lesson, answers a question or receives a notification. After a few years, a busy academy can carry millions of rows it never reads, and the admin, reports and logged-in pages slow down. LifterLMS database optimization is about removing that weight without touching the records your business depends on: enrollments, progress, grades, orders and certificates.

This guide is for site owners and developers with an established LifterLMS site. It shows how to measure what is actually large, explains every LifterLMS table and whether it can be cleaned, gives you a batched pruning script, and covers the WordPress-level cleanup that matters most on course sites.

For architecture-level changes on very large sites, such as database servers, indexes and background processing, see our guide to scaling LifterLMS for large sites. This article is the cleanup companion to it.

Measure before you clean

Cleanup tools that "optimize the database" without telling you what they will remove are the most common way course sites lose data. Start by finding out where the space actually is. This WP-CLI command lists the 25 largest tables:

wp db query "SELECT table_name AS tbl, table_rows AS approx_rows,
  ROUND( ( data_length + index_length ) / 1024 / 1024, 1 ) AS size_mb
  FROM information_schema.tables
  WHERE table_schema = DATABASE()
  ORDER BY ( data_length + index_length ) DESC
  LIMIT 25;"

Row counts from information_schema are estimates for InnoDB tables; use SELECT COUNT(*) on a specific table when you need the exact figure. Note the top five tables. On most LifterLMS sites they are some mix of wp_postmeta, wp_lifterlms_events, the Action Scheduler tables, wp_options and wp_lifterlms_user_postmeta, and only some of those are candidates for cleanup.

Take a full backup and test that it restores before you delete anything. Run every step on a staging copy first.

The LifterLMS tables: what is safe to clean

TableWhat it holdsClean it?
lifterlms_user_postmetaEnrollments, enrollment history, completions, award links, favouritesNo. This is the student record. Delete only through LifterLMS (for example, deleting a user).
lifterlms_quiz_attemptsEvery quiz attempt, with answers and gradesNo. Attempts drive grades, pass status and attempt limits. Removing them can give students extra attempts.
lifterlms_eventsSign-ons, sign-outs, session starts and ends, and client-side page eventsYes, with a retention policy. Old rows feed only activity history.
lifterlms_events_open_sessionsPointers to sessions that have not endedLeave it. LifterLMS removes rows as sessions end; it should stay small.
lifterlms_sessionsTemporary data such as notices and checkout stateAlready cleaned. Expired rows are deleted hourly.
lifterlms_notificationsOn-screen and email notification recordsYes, old rows. We found no scheduled cleanup in core.
lifterlms_lesson_time_sessionsLesson time tracking sessions (LifterLMS 10.1 and later)Only under a deliberate policy. They can be evidence for time-based requirements.
Voucher tables, lifterlms_api_keys, lifterlms_webhooksVouchers and redemptions, API keys, webhooksNo. Small and functional.

The pattern is simple. Anything that records what a student did for credit, or what a customer paid, stays. Activity logs and message records can go after a retention period you have agreed with whoever owns reporting and privacy. Our article on the LifterLMS data model explains these tables in more depth, and the official LifterLMS database description lists the meta keys in the user postmeta table.

Pruning old events and notifications safely

Large deletes on a live database cause locks, replication lag and slow pages. Delete in small batches, outside busy hours, with a dry run first. This script, run with wp eval-file, does that for the events and notifications tables. It refuses retention periods under 90 days and never removes the start event of a session that is still open.

<?php
/**
 * Prune old LifterLMS events or notifications in small batches.
 *
 * Dry run:  wp eval-file llmsx-prune.php events 730
 * Delete:   wp eval-file llmsx-prune.php events 730 run
 */

global $wpdb;

$targets = array(
	'events'        => array(
		'table'  => $wpdb->prefix . 'lifterlms_events',
		'column' => 'date',
		// Never remove the start event of a session that is still open.
		'extra'  => "AND id NOT IN ( SELECT event_id FROM {$wpdb->prefix}lifterlms_events_open_sessions )",
	),
	'notifications' => array(
		'table'  => $wpdb->prefix . 'lifterlms_notifications',
		'column' => 'created',
		'extra'  => '',
	),
);

$target = isset( $args[0] ) ? $args[0] : '';
$days   = isset( $args[1] ) ? absint( $args[1] ) : 0;
$run    = isset( $args[2] ) && 'run' === $args[2];

if ( ! isset( $targets[ $target ] ) || $days < 90 ) {
	WP_CLI::error( 'Usage: wp eval-file llmsx-prune.php <events|notifications> <days, at least 90> [run]' );
}

$t      = $targets[ $target ];
$cutoff = wp_date( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS );
$where  = $wpdb->prepare( "{$t['column']} < %s ", $cutoff ) . $t['extra'];

$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t['table']} WHERE {$where}" );
WP_CLI::log( sprintf( '%d rows in %s are older than %s.', $count, $t['table'], $cutoff ) );

if ( ! $run ) {
	WP_CLI::log( 'Dry run only. Add "run" to delete them.' );
	return;
}

do {
	$deleted = (int) $wpdb->query( "DELETE FROM {$t['table']} WHERE {$where} ORDER BY id LIMIT 5000" );
	WP_CLI::log( "Deleted {$deleted} rows." );
	usleep( 250000 ); // Give the database room to breathe between batches.
} while ( $deleted > 0 );

WP_CLI::success( 'Done. Run "wp cache flush" next.' );

Run the dry run, check the count makes sense, then add run. Afterwards, run wp cache flush. Deleting rows does not shrink InnoDB files on its own; if you need the disk space back, rebuild the table with OPTIMIZE TABLE during a quiet period, because it rebuilds the whole table.

Choose the retention period with care. Events show recent activity on reporting screens and record sign-on history, which some organisations treat as an audit trail. Two years is a common starting point for events; notification records are rarely needed after 90 to 180 days. If you need history beyond that, export the rows to an archive table or file before deleting.

To slow future growth, you can narrow client-side event tracking with the llms_tracking_post_types filter, as shown in the scaling guide.

Built-in LifterLMS tools that help

Under LifterLMS > Status > Tools & Utilities you will find several safe, targeted cleanups:

  • Student Progress Cache: Clear cache removes cached overall progress and grade values from user meta. Real progress is untouched, and the values rebuild when next needed.
  • User Sessions: Clear All User Sessions empties the sessions table. Expired sessions are already removed hourly, so use this only when troubleshooting.
  • Delete processor batches: removes leftover background-processing batches stored in wp_options, which can pile up if a processor stalls.
  • Delete course data locks: clears locks left behind by the course data background processor, which calculates course statistics.
  • Delete Legacy User Information Options: removes options used before LifterLMS 5.0 to control account fields.

Action Scheduler: the table that surprises people

LifterLMS uses Action Scheduler for recurring payments, expirations, delayed engagements and webhook deliveries, and many other plugins use it too. Its tables, wp_actionscheduler_actions and wp_actionscheduler_logs, often end up among the largest on a site.

  • Completed and canceled actions are purged automatically after 30 days by default. You can shorten that with the action_scheduler_retention_period filter.
  • Failed and past-due actions are not purged by that clean-up. A large number of them is a symptom, usually of WP-Cron not running or an add-on erroring, and deleting them hides the problem. Investigate them under LifterLMS > Status > Scheduled Actions first; a past-due llms_charge_recurring_payment is a renewal that has not happened.
  • Pending actions are your future. Never delete pending LifterLMS actions to save space. They include upcoming renewals and expirations.
<?php
// Keep completed and canceled Action Scheduler actions for 14 days instead of 30.
add_filter( 'action_scheduler_retention_period', function () {
	return 14 * DAY_IN_SECONDS;
} );

Several plugins bundle Action Scheduler and the newest bundled version is the one that runs, so the clean-up behaviour can vary slightly between sites. If the queue is backed up, our guide to LifterLMS WP-Cron problems covers the fix.

WordPress-level cleanup that matters on course sites

Autoloaded options

Options marked to autoload are loaded on every request, logged in or not. A few hundred kilobytes here slows every page. This query lists the largest:

wp db query "SELECT option_name, ROUND( LENGTH( option_value ) / 1024, 1 ) AS kb
  FROM $(wp db prefix)options
  WHERE autoload IN ( 'yes', 'on', 'auto', 'auto-on' )
  ORDER BY LENGTH( option_value ) DESC
  LIMIT 20;"

Look for leftovers from plugins you removed and oversized caches. Do not change LifterLMS's own settings options; if one is unexpectedly large, find out why first.

Transients

Expired transients in wp_options are removed by WordPress over time and by wp transient delete --expired. With a persistent object cache, transients live in memory instead, which is one more reason to run one on a LifterLMS site; see our guide to Redis object caching for LifterLMS.

Revisions

Lessons are edited often, and each save can add a revision. Limiting revisions with WP_POST_REVISIONS in wp-config.php and removing very old ones is reasonable. Keep at least a few, because they are your undo history for course content.

Orphaned meta

Post meta for deleted posts can be removed, but be careful with LifterLMS orders, transactions and access plans: their meta is the financial record. Only remove meta whose post genuinely no longer exists, and test the query on staging.

Common mistakes

  • Running a one-click "optimize" plugin on a course site without checking what it deletes. Some remove data other plugins still use.
  • Deleting quiz attempts to save space. It changes grades and resets attempt limits.
  • Clearing Action Scheduler wholesale. Pending renewals disappear with it.
  • Huge single DELETE statements on a live site, which can lock tables during peak hours.
  • No retention policy. Without one, the same debate happens every year and the data keeps growing.

Frequently asked questions

Which LifterLMS table gets the largest?

On busy sites, usually wp_lifterlms_events, followed by wp_lifterlms_user_postmeta. The first can be pruned under a retention policy; the second should not be.

Does LifterLMS clean up its own data?

Partly. Expired sessions are deleted hourly and temporary files daily. We found no scheduled clean-up of events or notifications in LifterLMS 10.3.

Will deleting old events affect reports?

Activity history and session information older than your cut-off disappear from reporting screens. Enrollment, progress and grade reports are unaffected.

How often should I clean the database?

Run the pruning script monthly or quarterly with the same retention period, and review table sizes twice a year.

Next steps

Run the table-size query today and write down the five largest tables. If none of them is a LifterLMS activity table or Action Scheduler, your slowness is probably somewhere else. If you would rather have the database audited, a retention policy agreed and the cleanup automated safely, our LifterLMS optimization service handles it. Send us your table-size output and we will tell you what is worth cleaning.

Add LifterLMS Expert to your preferred sources

Add lifterlmsexpert.com as a preferred source on Google, or open this article in your AI assistant to use it as a source.

  • Add as a preferred source on Google
Free consultation

Prefer expert help over DIY?

Skip the trial and error. Get specialist LifterLMS help and ship faster.

Talk to a LifterLMS Expert Explore our services

Replies within one business day