Fix 500 errors

We have not been able to write simple tests for these changes, but they resolve the issue on the staging server under load.