Should I store critical css in the database or in my theme’s filesystem?

Preface

It would be best to see what kind of caching options are available through your host. If you can use an object cache, CDN, or anything like that, you could decrease the load on your server.

If your database and webserver are the same host, then storing this in the database won’t necessarily mean there are fewer reads to the disk. A database is just a way to map data from the filesystem to something reasonable to query, and to some degree requires reading/writing to the filesystem (although it does do some amount of caching as well).

So, what to do?

I would suggest some means of Object Cache. Install something like Redis – Redis provides several means of persistence, so don’t let the “in-memory data structure” part fool you.

Once you have an object cache of some kind set up with WordPress (there are plugins for many popular options, including Redis), you can interface with the cache using WordPress’s own internal methods.

Setting and Invalidating Cached Data

function get_cached_css( $post_id ) {
    $css_hash = generate_your_hash();
    $css      = wp_cache_get( $css_hash, 'css' );

    if ( ! $css ) {
        $css = generate_css();

        // Purge any previous CSS.
        $old_css = get_post_meta( $post_id, 'custom-css-key', true );

        if ( $old_css ) {
            wp_cache_delete( $old_css, 'css' );
        }

        wp_cache_set( $css_hash, $css, 'css' );
        update_post_meta( $post_id, 'custom-css-key', $css_hash );
    }

    return $css;
}

Fill in the methods to fit what you have for generating the CSS’s hash and file.

Then, in your template:

$css = get_cached_css( get_the_ID() );
// etc...