by maxcountryman

maxcountryman /flake

Decentralized, k-ordered unique IDs in Clojure

130 Stars 9 Forks Last release: Not found BSD 3-Clause "New" or "Revised" License 77 Commits 10 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:


Clojars Project Build Status Dependencies Status

Decentralized, k-ordered unique ID generator.

This is a Clojure implementation of Boundary's Erlang Flake ID service.


New flake IDs can be generated with the

fn from flake's core namespace.

Note that in order to prevent generation of duplicate IDs,

must be called prior to generating IDs for the first time.

For example:

=> (require '[flake.core :as flake])
=> (flake/init!)
=> (map flake/flake->bigint (take 3 (repeatedly flake/generate!)))

Here we have generated three BigIntegers which are flake IDs. Note how they are ordered.

It may be desirable to encode these IDs in a shorter representation, such as Base62. The utils namespace provides an encoder:

=> (require '[flake.utils :as utils])
=> (->> (repeatedly flake/generate!)

A flake's middle-most bits are derived from a hardware address, e.g. MAC. If this is not desirable or the caller wishes to have more granular control over which bits are used here, a custom

may be provided:
(import '[java.security SecureRandom])

(defn rand-bytes "Return n random bytes in an array." [n] (let [bs (byte-array n)] (.nextBytes (SecureRandom.) bs) bs))

(def worker-id (rand-bytes 6))

(first (repeatedly (partial flake/generate! worker-id)))

The above specifies a random array of bytes to be used as the worker-id.


Flakes are byte sequences composed of 128 bits. These sequences are structured such that the first 64 bits are a timestamp, i.e. the time since an epoch in milliseconds, the next 48 bits are a unique, machine-specific bitset, normally the MAC, and finally the remaining 16 bits are a monotonically increasing short.

A diagram of the flake byte structure:



Exceptions may occur if a single machine generates more than 65,535 flakes within a millisecond. That puts the upper-bound on flake generation per machine at ~65 million flakes per second. If this limit is reached a

will be raised.

Additionally flake makes an effort to detect drift in system time and will raise

if time appears to be flowing in the wrong direction. Note that
must be used for this to work properly!

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.