Fun with /tmp

Using memory for cache directories in Linux

Fun with /tmp
Photo by Kevin Horvat / Unsplash

Although SSD lifespans have come a long way, I still don’t like unnecessary writes if they can be easily avoided*. Not only that, but performance is significantly faster when reading cached data from RAM vs from disk.

Assuming sufficient free memory, here is one approach:

In /etc/fstab, add this line:

tmpfs /tmp tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777,size=4096M 0 0

Reboot. This creates a file system /tmp of 4GB, in RAM.

Then, as your normal user do:

mv .cache/ .cacheold
ln -s /tmp/ .cache

This creates a symlink to /tmp called .cache, which means that Firefox, Chrome, Chromium, and other applications will create their cache directories in /tmp, in memory, instead of in the usual .cache/ directory on the SSD. (You can further limit cache sizes in Firefox, Chrome, etc., as desired.)

Of course, the contents of /tmp will be lost on every reboot. There may be applications which misuse the cache directory to store persistent settings. One could work around this by creating individual symlinks for each application—for example, linking .cache/mozilla to /tmp—but this would become messy, cumbersome, or both.

Instead, I prefer to fix each application as needed. This solution works well:

sudo crontab -e

Add these lines:

@reboot bash /root/bin/

Then create a file /root/bin/ consisting of:
mkdir -p /tmp/my_bad_app
cp /home/my_username/config/my_bad_app.ini /tmp/my_bad_app/

...where my_bad_app is the name of your misbehaving application and my_bad_app.ini is the name of the ini or other config file needed for the application to function properly. (Use the .cacheold directory you created above to get a good copy of whatever config files you need to re-create in this fashion.)

You can do likewise for any other files/directories which should be volatile for your specific use case. Some of them may make sense to modify as described above, while others (for example, /var/yum/cache or /var/log) may make more sense to mount directly as a tmpfs in /etc/fstab.

*I also like to track SSD writes over time, so I will know when a drive is nearing end-of-life. I schedule this script to run every 30 minutes in root’s crontab (you will need to adjust the device names and calculations to fit your situation):

# /root/bin/ to be scheduled every 30 minutes
echo `date +%Y%m%d`T`date +%H%M%S`,`/usr/sbin/smartctl -A /dev/sdc | awk '/^241/ {print $10 * 512 / 1024 ^ 4 }'`,sda >> /var/log/ssd_tracking.log
echo `date +%Y%m%d`T`date +%H%M%S`,`/usr/sbin/nvme smart-log /dev/nvme0n1 | awk '/data_units_written/ {print $3 * 512000 / 1024 ^ 3}'`,nvme >> /var/log/ssd_tracking.log

This results in a log which looks something like this:

Found this post insightful, funny, or useful? Consider supporting us.

Support Us