mdbid

1.0.0 • Public • Published

view on npm downloads per month node version build status test coverage license

mdbid

This package can be used to generate unique string identifiers in a very performant way. The algorithm is identical to the one that MongoDB uses to create its document identifiers.

Usage

 
const oid = require('mdbid')
 
oid() // '579b64ac12b43732a08531d8'
 

API

mdbid()string
mdbid.machineId: 3-byte integer to use as machine identifier.
mdbid.processId: 2-byte integer to use as process identifier.
mdbid.sequence: Initial value of the sequence counter. It's a 3-byte integer.
mdbid.version: The version string from package manifest.

Installation

With npm:

npm install mdbid

Benchmark

The benchmark measures elapsed time it takes to perform 1500000 calls. (Which means that lower values are better.)

Here are the results of similar packages:

bson: 1571ms
mdbid: 593ms
mongoid: 6153ms
objectid: 6154ms
mongoid-js: 396ms

Motivation

In many of my projects Redis is used as the primary database, which means that it's not just the caching layer of the system, but actual documents (users, sessions, accounts, etc.) are stored in it.

Thus I need identifiers to include in Redis keys, but Redis does not provide any built-in solution for id generation.

It is true that you can create incremental numeric ids easily with atomic counters, but those ids are only identical per schema and a user can predict new ids. And that's unacceptable in a lot of real-life situations.

Mongo's id model seems like a good choice, because ids are guaranteed to be unique per server per process up to a really huge (2^(5*8)) cluster of servers (with proper configuration). So I decided to use it.

There are some already existing packages out there with the same purpose but some of them

  • are inefficient when the expected output is string
  • are not identical to Mongo's object id specification (last three bytes of an id must be a "counter, starting with a random value")
  • are not well-tested despite they're providing an unnecessarily complex API.

mongoid-js seemed like the best approach, but

  • it's code is unmaintained and messy
  • it not follows Node's code-style standards
  • the use of timers makes it not truly sync and counting calls can have unintended side effects.

So I decided to re-implement it in a sustainable manner. That's the story of mdbid.

License

MIT

Dependencies (1)

Dev Dependencies (5)

Package Sidebar

Install

npm i mdbid

Weekly Downloads

655

Version

1.0.0

License

MIT

Last publish

Collaborators

  • schwarzkopfb