 Future = Npm.require 'fibers/future'
 
 globals = @
+
+# From Meteor's random/random.js
+UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz'
+
+INSTANCES = parseInt(process.env.PEERDB_INSTANCES ? 1)
+INSTANCE = parseInt(process.env.PEERDB_INSTANCE ? 0)
+
+throw new Error "Invalid number of instances: #{ INSTANCES }" unless 0 <= INSTANCES <= UNMISTAKABLE_CHARS.length
+throw new Error "Invalid instance index: #{ INSTANCE }" unless (INSTANCES is 0 and INSTANCE is 0) or 0 <= INSTANCE < INSTANCES
+
+# TODO: Support also other types of _id generation (like ObjectID)
+PREFIX = UNMISTAKABLE_CHARS.split ''
+
+if INSTANCES > 1
+  range = UNMISTAKABLE_CHARS.length / INSTANCES
+  PREFIX = PREFIX[Math.round(INSTANCE * range)...Math.round((INSTANCE + 1) * range)]
 
 # Fields:
 #   serial

  # (Otherwise setupObservers would trigger strange exceptions anyway)
  globals.Document.defineAll()

  migrations()

  setupObservers()

Document = globals.Document


      currentSchema = newSchema
      currentName = newName

    # We do not check for not migrated documents if we are skipping migrations
    unless process.env.PEERDB_SKIP_MIGRATIONS
      # For all those documents which lack schema information we assume they have the last schema
      @Meta.collection.update
        _schema:
          $exists: false
      ,
        $set:
          _schema: currentSchema
      ,
        multi: true

      notMigrated = _.pluck @Meta.collection.find(
        _schema:
          $ne: currentSchema
      ,
        fields:
          _id: 1
      ).fetch(), '_id'

      throw new Error "Not all documents migrated to the latest schema version (#{ currentSchema }): #{ notMigrated }" if notMigrated.length

    @Meta.schema = currentSchema

