 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

    initializing = true

    observers =
      added: catchErrors (id, fields) =>
        @_sourceUpdated id, fields if updateAll or not initializing

    unless updateAll
      observers.changed = catchErrors (id, fields) =>
        @_sourceUpdated id, fields

    handle = @Meta.collection.find({}, fields: sourceFields).observeChanges observers

  projection

# TODO: Should we add retry?
observerCallback = (f) ->
  return (id, args...) ->
    try
      # We call f only if the first character of id is in PREFIX.
      # By that we allow each instance to operate only on a subset
      # of documents, allowing simple coordination while scaling.
      f id, args... if id[0] in PREFIX
    catch e
      Log.error "PeerDB exception: #{ e }: #{ util.inspect args, depth: 10 }"
      Log.debug e.stack
