Put ID lookup code into its own function.
Fix too-aggressive setting of last_failure.