SyntaxStudy
Sign Up
MySQL Session and Cache Cleanup
MySQL Beginner 3 min read

Session and Cache Cleanup

Session Cleanup

Use events to automatically purge expired sessions, tokens, and cache entries from the database.

Example
CREATE EVENT cleanup_expired_sessions
ON SCHEDULE EVERY 15 MINUTE
DO
BEGIN
  DELETE FROM sessions WHERE last_activity < UNIX_TIMESTAMP() - 7200;  -- 2h timeout
  DELETE FROM password_resets WHERE created_at < NOW() - INTERVAL 1 HOUR;
  DELETE FROM email_verification_tokens WHERE expires_at < NOW();
  DELETE FROM cache WHERE expiration < UNIX_TIMESTAMP();
END;
Pro Tip

Add an index on the expiry column — without it, cleanup deletes become full-table scans.