By adding the service id, the query performance has improved greatly. It went from 6200ms to 0.04ms. This should stop the 500s when a template is deleted.