Second attempt to fix race conditions in cache write. Psql compatible this time.