Never Pay your Mortgage


    1.0.0 • Public • Published

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


    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.


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


    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.


    With npm:

    npm install mdbid


    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


    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.




    npm i mdbid

    DownloadsWeekly Downloads






    Last publish


    • schwarzkopfb