snowflake4s

Overview

GitHub Workflow Status Maven Central scaladoc license Scala Steward badge

snowflake4s is a purely functional library used for generating unique ids, using Twitter’s snowflake id format.

sbt
libraryDependencies += "io.github.qwbarch" %% "snowflake4s" % "1.1.0-RC1"
Maven
<properties>
  <scala.binary.version>3</scala.binary.version>
</properties>
<dependencies>
  <dependency>
    <groupId>io.github.qwbarch</groupId>
    <artifactId>snowflake4s_${scala.binary.version}</artifactId>
    <version>1.1.0-RC1</version>
  </dependency>
</dependencies>
Gradle
def versions = [
  ScalaBinary: "3"
]
dependencies {
  implementation "io.github.qwbarch:snowflake4s_${versions.ScalaBinary}:1.1.0-RC1"
}

Quick example

Here is a minimal example to create a snowflake id (Scala 3):

import cats.syntax.all.given
import cats.effect.IO
import cats.effect.IOApp
import cats.effect.std.Console
import org.typelevel.log4cats.Logger
import org.typelevel.log4cats.slf4j.Slf4jLogger
import io.github.qwbarch.snowflake4s.IdWorkerBuilder

object Main extends IOApp.Simple:

   override def run: IO[Unit] =
      given Logger[IO] = Slf4jLogger.getLogger[IO]
      for
         idWorker <- IdWorkerBuilder.default[IO].build
         id <- idWorker.nextId
         _ <- Console[IO].println(id)
      yield ()

Customizing id workers

A custom epoch, sequence, worker id, and data center id can be provided through the IdWorkerBuilder.

IdWorkerBuilder.default[IO]
   .withWorkerId(0)
   .withDataCenterId(0)
   .withEpoch(IdWorker.TwitterEpoch)
   .withSequence(0)
   .build

Running tests

To run snowflake4s’ unit tests, simply enter the following command:

sbt test

Alternative libraries

  • scala-id-generator - If you’re looking to generate snowflake ids imperatively, try out this library from lightbend!
  • fuuid - Looking for something more lightweight than snowflakes? This is a purely functional library for generating UUID’s.

Credits

Full credits goes to Twitter. Implementation is from Twitter’s archives.