systemd tmpfs shadow directory -- copy to/from ram and back when (u)mount-ing

I'd like to keep some directories (e.g. /var/cache/apt, /var/lib/apt/lists, user browser caches or even Mozilla profiles) in RAM, but still backed by disk. The files should be copied to RAM when mounting and copied back to disk when umounting.

Short of writing a oneshot systemd unit (I've done this, but I don't like it), what options do I have? Adding a tmpfs entry to /etc/fstab is the simplest, but doesn't copy to/from disk.

Also, for user files (e.g. ~/.cache) can I use a systemd --user unit, so that it applies / can be configured to individual users independently?


Do not use tmpfs for persistent storage. If this copy script does not run, such as when the host crashes, it is gone.

Use persistent disk volumes. Perhaps not backed up and less redundant than important data, but durable.

Linux already uses available RAM for caching. So those recently accessed files are in RAM when you check for software updates again, or hit the back button in the browser. Further, as the files already are on durable storage, these caches can be reclaimed immediately if the system needs RAM for other reasons.