Published on

Automatic deletion of binlog files with MySQL

By inspecting my server metrics, I realized that my 50GB disk was almost full while this site hosts very few files and contains mostly text data.

Identify folders using the most disk space

So I used the command du -h / 2>/dev/null | grep '[0-9\.]\+G' to find the folders on my server that were taking up the most space.

I then saw that my /var/lib/mysql folder weighed nearly 30GB and was filled with binlog.xxxxxx files.

MySQL binlog files

These files are binary log files that record transactions performed on the database. They are useful when using replication, for data recovery or as an audit log.

In my case, these files are not very useful to me and so I wanted to set up a mechanism to automatically delete them.

If you are using MariaDB, the binlog_expire_logs_seconds system variable allows you to specify the number of seconds after which the logs will be purged when they are rotated or when MySQL starts.

So I opted for a conservative value of 6 hours as specified in the MariaDB documentation on this subject by adding this statement to my my.cnf file.

[mariadb]
binlog_expire_logs_seconds=21600

Purge older binlog files

To purge the old binary log files, I used this command PURGE BINARY LOGS TO 'binlog.xxxxxx'; where xxxxxx is the index of the latest log that will be deleted.

With this configuration, I was able to recover almost all the space used by MySQL and drop my server's disk space usage below 10%.