Reduced the number of database calls in the initial part of create_instance() without changing the logic (such as it is)
While preserving same legacy logic, reduced the number of queries, especially on Instance
Made saving attachments into a separate thread, so that create_instance() can return w/o waiting for all media to be saved
Like other optimizations, attempt to fetch the single, expected duplicate in one shot, rather that filter and index 0
More tweaks to make the legacy creation logic work within the context of a more efficient set of queries (Formhub is not easy)
Restore async flag for ParsedInstance save, since it it needed by mongodb; also explicitly turned autocommit (the default) on, in case it was turned off somewhere else...
Reluctantly switched back to saving attachment files serially, before instance returns (potentially still slow, but less likely to create integreity errors)
Refuse to give up on saving the media attachments in a separate thread, since it would be a huge time improvement in server response.
This approach tries passing the Instance pk to the thread, and have the object look it up before starting (should work in theory).
Just to check about a suspicion about why the tests fail:
the test User is being deleted immeidately after this returns,
while the thread saving attachments may still be working.
IRL, this condition would not occur, but just to confirm,
introducing an artificial pause for letting the attachment
saving thread to finish.
Sleeping 2 min per create_instance() was excessive, especially since just trying to prove a point, so made it 3 sec (hope that's enough to test this theory)
Just realized that to check the theory properly, need to sleep in both places the attachment-saving thread is started (the next question is: is 3 seconds enough?)
Alas, formhub test suite, how much time do you need?
Used QuerySet.values_list() for checking for duplicates, rather than loading entire objects into memory
*sigh* have to do it again: Reluctantly switched back to saving attachment files serially, before instance returns (potentially still slow, but less likely to create integreity errors)
Fixed typo in serial attachment saving function
Merge pull request #1333 from SEL-Columbia/slightly_better_create_instance

Slightly better create instance