Forgot to close files when scanning at startup
Lock db as soon as we decide on an unused id

Also, no need to actually calculate a random id until we know that the request
is valid.