First, the context. Then, the question.
I have the need for a database to exist in a sort of “pre-provisioned” state, with certain - call them “original” - collections existing (with no documents) that have uniqueIndexes applied (prior to any writes, of course). Then, at runtime, I am dynamically creating collections - call them “novel” - to which I apply uniqueIndexes immediately.
The problem is that multiple applications will be starting independently, each with write access to the “original” collections. There’s no clear point at which unique-createIndexes should be applied, unlike the “novel” collections which can be uniquely-indexed by the application which creates them at runtime. I am considering 2 approaches to the “provisioning” of these “original” collections’ indexes:
- Create a separate application whose responsibility is only to uniquely index/provision these “original” collections. Upon successful termination of this application, the N independent applications which have write access to these “original” collections can safely assume that these collections have been uniquely indexed and don’t have to perform any findOne/findAll prior to document insertion.
- Have each independent application attempt to index the “original” collections independently, inevitable encountering an error like “ErrIndexAlreadyExists” (a fabricate error name). This is what I was doing, but it relies on the particular error string, which might change with a different version of the mongo-go-driver.
The 1st approach has the disadvantage of an extra and awkward step in the deployment procedure. Also, if someone forgets to run this application (i.e. ./buildIndexes) then there’s no failsafe. The disadvantage of the second case is two-pronged: 1) it relies on the error string (this can probably be avoided using an error value I’m not aware of); 2) it (kind of) requires each application to take the responsibility of indexing these collections, duplicating work.
My question is this: What is the best practice/recommended procedure for establishing a unique set of indexes on a set of collections that a developer knows will be written to independently by multiple applications?