> An operation is idempotent if performing it multiple times yields the same result as performing it exactly once. And then he casually offers an API that does different things on first and second call as the "good" example. If you have a "create a virtual machine" API it better create a fucking virtual machine. If I call the damn thing twice, I expect to have two VMs. If there is some sort of unique argument like cr…
With an idempotent API, starting a VM and doing something with it can look like this: let new_id = generate_id(); retry_with_backoff(() => api.make_vm(new_id)); retry_with_backoff(() => api.do_thing_with_vm(new_id)); This works even if any individual API calls fail, or if the API call makes it to the API server but the response fails to make it to the client. If the APIs aren't idempotent, then you would have to do t…
try:
vm_id = api.make_vm()
except SomeError as e:
log.error(e)
else:
res = api.do_thing_with_vm(vm_id)
and in your example, if we are generating ids ourselves, we still have to verify that we got the right VM. If your ids are provably unique, there is no reason to generate them, the API can take care of that, but if you want something like a named entity, you have a problem. What if the name is already taken? So your code would look more like new_id = generate_id()
try:
vm = api.get_vm(new_id)
except VM_DoesNotExist:
vm = api.make_vm(new_id)
except SomeError as e:
log.error(e)
else:
api.do_thing_with_vm(new_id)
because if the make_vm API simply returns a VM whether it was created or not, it is entirely possible that you are getting a VM that is busy doing something else for some other process.