Make the database backend retry more reliable

This should fix #1786. However I haven't run the stress tests yet.