{"id":13602033,"url":"https://github.com/baidu/uid-generator","last_synced_at":"2025-05-14T13:06:58.830Z","repository":{"id":37359350,"uuid":"86289901","full_name":"baidu/uid-generator","owner":"baidu","description":"UniqueID generator","archived":false,"fork":false,"pushed_at":"2023-05-31T08:04:59.000Z","size":390,"stargazers_count":5510,"open_issues_count":40,"forks_count":1562,"subscribers_count":247,"default_branch":"master","last_synced_at":"2025-04-11T06:08:29.454Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/baidu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-03-27T04:03:43.000Z","updated_at":"2025-04-11T05:58:55.000Z","dependencies_parsed_at":"2023-10-20T18:15:15.384Z","dependency_job_id":null,"html_url":"https://github.com/baidu/uid-generator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fuid-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fuid-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fuid-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fuid-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/baidu","download_url":"https://codeload.github.com/baidu/uid-generator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254149955,"owners_count":22022851,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T18:01:12.243Z","updated_at":"2025-05-14T13:06:53.821Z","avatar_url":"https://github.com/baidu.png","language":"Java","funding_links":[],"categories":["Java","中间件","分布式开发"],"sub_categories":[],"readme":"UidGenerator\n==========================\n[In Chinese 中文版](README.zh_cn.md)\n\nUidGenerator is a Java implemented, [Snowflake](https://github.com/twitter/snowflake) based unique ID generator. It\nworks as a component, and allows users to override workId bits and initialization strategy. As a result, it is much more\nsuitable for virtualization environment, such as [docker](https://www.docker.com/). Besides these, it overcomes\nconcurrency limitation of Snowflake algorithm by consuming future time; parallels UID produce and consume by caching\nUID with RingBuffer; eliminates CacheLine pseudo sharing, which comes from RingBuffer, via padding. And finally, it\ncan offer over \u003cfont color=red\u003e6 million\u003c/font\u003e QPS per single instance.\n\nRequires：[Java8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)+,\n[MySQL](https://dev.mysql.com/downloads/mysql/)(Default implement as WorkerID assigner; If there are other implements, MySQL is not required)\n\nSnowflake\n-------------\n![Snowflake](doc/snowflake.png)  \n** Snowflake algorithm：** An unique id consists of worker node, timestamp and sequence within that timestamp. Usually,\nit is a 64 bits number(long), and the default bits of that three fields are as follows:\n\n* sign(1bit)  \n  The highest bit is always 0.\n\n* delta seconds (28 bits)  \n  The next 28 bits, represents delta seconds since a customer epoch(2016-05-20). The maximum time will be 8.7 years.\n\n* worker id (22 bits)  \n  The next 22 bits, represents the worker node id, maximum value will be 4.2 million. UidGenerator uses a build-in\n  database based ```worker id assigner``` when startup by default, and it will dispose previous work node id after\n  reboot. Other strategy such like 'reuse' is coming soon.\n\n* sequence (13 bits)   \n  the last 13 bits, represents sequence within the one second, maximum is 8192 per second by default.\n  \n**The parameters above can be configured in spring bean**\n\n\nCachedUidGenerator\n-------------------\nRingBuffer is an array，each item of that array is called 'slot', every slot keeps a uid or a flag(Double RingBuffer).\nThe size of RingBuffer is 2^\u003csup\u003en\u003c/sup\u003e, where n is positive integer and equal or greater than bits of\n```sequence```. Assign bigger value to ```boostPower``` if you want to enlarge RingBuffer to improve throughput.\n\n###### Tail \u0026 Cursor pointer\n* Tail Pointer\n\n  Represents the latest produced UID. If it catches up with cursor, the ring buffer will be full, at that moment, no put\n  operation should be allowed, you can specify a policy to handle it by assigning\n  property ```rejectedPutBufferHandler```.\n  \n* Cursor Pointer\n\n  Represents the latest already consumed UID. If cursor catches up with tail, the ring buffer will be empty, and\n  any take operation will be rejected. you can also specify a policy to handle it  by assigning\n  property ```rejectedTakeBufferHandler```.\n\n![RingBuffer](doc/ringbuffer.png)  \n\nCachedUidGenerator used double RingBuffer，one RingBuffer for UID, another for status(if valid for take or put)\n\nArray can improve performance of reading, due to the CUP cache mechanism. At the same time, it brought the side\neffect of 「False Sharing」, in order to solve it, cache line padding is applied.\n\n![FalseSharing](doc/cacheline_padding.png) \n\n#### RingBuffer filling\n* Initialization padding\n  During RingBuffer initializing，the entire RingBuffer will be filled.\n  \n* In-time filling\n  Whenever the percent of available UIDs is less than threshold ```paddingFactor```, the fill task is triggered. You can\n  reassign that  threshold in Spring bean configuration.\n  \n* Periodic filling\n  Filling periodically in a scheduled thread. The```scheduleInterval``` can be reassigned in Spring bean configuration.\n\n\nQuick Start\n------------\nHere we have a demo with 4 steps to introduce how to integrate UidGenerator into Spring based projects.\u003cbr/\u003e\n\n### Step 1: Install Java8, Maven, MySQL\nIf you have already installed maven, jdk8+ and Mysql or other DB which supported by Mybatis, just skip to next.\u003cbr/\u003e\nDownload [Java8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html),\n[MySQL](https://dev.mysql.com/downloads/mysql/) and [Maven](https://maven.apache.org/download.cgi),\nand install jdk, mysql. For maven, extracting and setting MAVEN_HOME is enough.\n\n#### Set JAVA_HOME \u0026 MAVEN_HOME\nHere is a sample script to set JAVA_HOME and MAVEN_HOME\n```shell\nexport MAVEN_HOME=/xxx/xxx/software/maven/apache-maven-3.3.9\nexport PATH=$MAVEN_HOME/bin:$PATH\nJAVA_HOME=\"/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home\";\nexport JAVA_HOME;\n```\n\n### Step 2: Create table WORKER_NODE\nReplace ```xxxxx``` with real database name, and run following script to create table,\n```sql\nDROP DATABASE IF EXISTS `xxxx`;\nCREATE DATABASE `xxxx` ;\nuse `xxxx`;\nDROP TABLE IF EXISTS WORKER_NODE;\nCREATE TABLE WORKER_NODE\n(\nID BIGINT NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',\nHOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name',\nPORT VARCHAR(64) NOT NULL COMMENT 'port',\nTYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER',\nLAUNCH_DATE DATE NOT NULL COMMENT 'launch date',\nMODIFIED TIMESTAMP NOT NULL COMMENT 'modified time',\nCREATED TIMESTAMP NOT NULL COMMENT 'created time',\nPRIMARY KEY(ID)\n)\n COMMENT='DB WorkerID Assigner for UID Generator',ENGINE = INNODB;\n```\n\nReset property of 'jdbc.url', 'jdbc.username' and 'jdbc.password' in [mysql.properties](src/test/resources/uid/mysql.properties).\n\n### Step 3: Spring configuration\n#### DefaultUidGenerator\nThere are two implements of UidGenerator: [DefaultUidGenerator](src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java), [CachedUidGenerator](src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java).\u003cbr/\u003e\nFor performance sensitive application, CachedUidGenerator is recommended.\n\n```xml\n\u003c!-- DefaultUidGenerator --\u003e\n\u003cbean id=\"defaultUidGenerator\" class=\"com.baidu.fsg.uid.impl.DefaultUidGenerator\" lazy-init=\"false\"\u003e\n    \u003cproperty name=\"workerIdAssigner\" ref=\"disposableWorkerIdAssigner\"/\u003e\n\n    \u003c!-- Specified bits \u0026 epoch as your demand. No specified the default value will be used --\u003e\n    \u003cproperty name=\"timeBits\" value=\"29\"/\u003e\n    \u003cproperty name=\"workerBits\" value=\"21\"/\u003e\n    \u003cproperty name=\"seqBits\" value=\"13\"/\u003e\n    \u003cproperty name=\"epochStr\" value=\"2016-09-20\"/\u003e\n\u003c/bean\u003e\n \n\u003c!-- Disposable WorkerIdAssigner based on Database --\u003e\n\u003cbean id=\"disposableWorkerIdAssigner\" class=\"com.baidu.fsg.uid.worker.DisposableWorkerIdAssigner\" /\u003e\n\n```\n\n#### CachedUidGenerator\nCopy beans of CachedUidGenerator to 'test/resources/uid/cached-uid-spring.xml'.\n```xml\n\u003c!-- CachedUidGenerator --\u003e\n\u003cbean id=\"cachedUidGenerator\" class=\"com.baidu.fsg.uid.impl.CachedUidGenerator\"\u003e\n    \u003cproperty name=\"workerIdAssigner\" ref=\"disposableWorkerIdAssigner\" /\u003e\n \n    \u003c!-- The config below is option --\u003e\n    \u003c!-- Specified bits \u0026 epoch as your demand. No specified the default value will be used --\u003e\n    \u003cproperty name=\"timeBits\" value=\"29\"/\u003e\n    \u003cproperty name=\"workerBits\" value=\"21\"/\u003e\n    \u003cproperty name=\"seqBits\" value=\"13\"/\u003e\n    \u003cproperty name=\"epochStr\" value=\"2016-09-20\"/\u003e\n    \u003c!-- RingBuffer size, to improve the throughput. --\u003e\n    \u003c!-- Default as 3. Sample: original bufferSize=8192, after boosting the new bufferSize= 8192 \u003c\u003c 3 = 65536 --\u003e\n    \u003cproperty name=\"boostPower\" value=\"3\"\u003e\u003c/property\u003e\n \n    \u003c!-- In-time padding, available UIDs percentage(0, 100) of the RingBuffer, default as 50 --\u003e\n    \u003c!-- Sample: bufferSize=1024, paddingFactor=50 -\u003e threshold=1024 * 50 / 100 = 512. --\u003e\n    \u003c!-- When the rest available UIDs \u003c 512, RingBiffer will be padded in-time --\u003e\n    \u003cproperty name=\"paddingFactor\" value=\"50\"\u003e\u003c/property\u003e\n \n    \u003c!-- Periodic padding --\u003e\n    \u003c!-- Default is disabled. Enable as below, scheduleInterval unit as Seconds. --\u003e\n    \u003cproperty name=\"scheduleInterval\" value=\"60\"\u003e\u003c/property\u003e\n \n    \u003c!-- Policy for rejecting put on RingBuffer --\u003e\n    \u003cproperty name=\"rejectedPutBufferHandler\" ref=\"XxxxYourPutRejectPolicy\"\u003e\u003c/property\u003e\n \n    \u003c!-- Policy for rejecting take from RingBuffer --\u003e\n    \u003cproperty name=\"rejectedTakeBufferHandler\" ref=\"XxxxYourTakeRejectPolicy\"\u003e\u003c/property\u003e\n \n\u003c/bean\u003e\n \n\u003c!-- Disposable WorkerIdAssigner based on Database --\u003e\n\u003cbean id=\"disposableWorkerIdAssigner\" class=\"com.baidu.fsg.uid.worker.DisposableWorkerIdAssigner\" /\u003e\n \n\u003c!-- Mybatis config... --\u003e\n```\n\n#### Mybatis config\n[mybatis-spring.xml](src/test/resources/uid/mybatis-spring.xml) shows as below:\n```xml\n\u003c!-- Spring annotation scan --\u003e\n\u003ccontext:component-scan base-package=\"com.baidu.fsg.uid\" /\u003e\n\n\u003cbean id=\"sqlSessionFactory\" class=\"org.mybatis.spring.SqlSessionFactoryBean\"\u003e\n    \u003cproperty name=\"dataSource\" ref=\"dataSource\" /\u003e\n    \u003cproperty name=\"mapperLocations\" value=\"classpath:/META-INF/mybatis/mapper/M_WORKER*.xml\" /\u003e\n\u003c/bean\u003e\n\n\u003c!-- transaction --\u003e\n\u003ctx:annotation-driven transaction-manager=\"transactionManager\" order=\"1\" /\u003e\n\n\u003cbean id=\"transactionManager\" class=\"org.springframework.jdbc.datasource.DataSourceTransactionManager\"\u003e\n\t\u003cproperty name=\"dataSource\" ref=\"dataSource\" /\u003e\n\u003c/bean\u003e\n\n\u003c!-- Mybatis Mapper scan --\u003e\n\u003cbean class=\"org.mybatis.spring.mapper.MapperScannerConfigurer\"\u003e\n\t\u003cproperty name=\"annotationClass\" value=\"org.springframework.stereotype.Repository\" /\u003e\n\t\u003cproperty name=\"basePackage\" value=\"com.baidu.fsg.uid.worker.dao\" /\u003e\n\t\u003cproperty name=\"sqlSessionFactoryBeanName\" value=\"sqlSessionFactory\" /\u003e\n\u003c/bean\u003e\n\n\u003c!-- datasource config --\u003e\n\u003cbean id=\"dataSource\" parent=\"abstractDataSource\"\u003e\n\t\u003cproperty name=\"driverClassName\" value=\"${mysql.driver}\" /\u003e\n\t\u003cproperty name=\"maxActive\" value=\"${jdbc.maxActive}\" /\u003e\n\t\u003cproperty name=\"url\" value=\"${jdbc.url}\" /\u003e\n\t\u003cproperty name=\"username\" value=\"${jdbc.username}\" /\u003e\n\t\u003cproperty name=\"password\" value=\"${jdbc.password}\" /\u003e\n\u003c/bean\u003e\n\n\u003cbean id=\"abstractDataSource\" class=\"com.alibaba.druid.pool.DruidDataSource\" destroy-method=\"close\"\u003e\n\t\u003cproperty name=\"filters\" value=\"${datasource.filters}\" /\u003e\n\t\u003cproperty name=\"defaultAutoCommit\" value=\"${datasource.defaultAutoCommit}\" /\u003e\n\t\u003cproperty name=\"initialSize\" value=\"${datasource.initialSize}\" /\u003e\n\t\u003cproperty name=\"minIdle\" value=\"${datasource.minIdle}\" /\u003e\n\t\u003cproperty name=\"maxWait\" value=\"${datasource.maxWait}\" /\u003e\n\t\u003cproperty name=\"testWhileIdle\" value=\"${datasource.testWhileIdle}\" /\u003e\n\t\u003cproperty name=\"testOnBorrow\" value=\"${datasource.testOnBorrow}\" /\u003e\n\t\u003cproperty name=\"testOnReturn\" value=\"${datasource.testOnReturn}\" /\u003e\n\t\u003cproperty name=\"validationQuery\" value=\"${datasource.validationQuery}\" /\u003e\n\t\u003cproperty name=\"timeBetweenEvictionRunsMillis\" value=\"${datasource.timeBetweenEvictionRunsMillis}\" /\u003e\n\t\u003cproperty name=\"minEvictableIdleTimeMillis\" value=\"${datasource.minEvictableIdleTimeMillis}\" /\u003e\n\t\u003cproperty name=\"logAbandoned\" value=\"${datasource.logAbandoned}\" /\u003e\n\t\u003cproperty name=\"removeAbandoned\" value=\"${datasource.removeAbandoned}\" /\u003e\n\t\u003cproperty name=\"removeAbandonedTimeout\" value=\"${datasource.removeAbandonedTimeout}\" /\u003e\n\u003c/bean\u003e\n\n\u003cbean id=\"batchSqlSession\" class=\"org.mybatis.spring.SqlSessionTemplate\"\u003e\n\t\u003cconstructor-arg index=\"0\" ref=\"sqlSessionFactory\" /\u003e\n\t\u003cconstructor-arg index=\"1\" value=\"BATCH\" /\u003e\n\u003c/bean\u003e\n```\n\n### Step 4: Run UnitTest\nRun [CachedUidGeneratorTest](src/test/java/com/baidu/fsg/uid/CachedUidGeneratorTest.java), shows how to generate / parse UniqueID:\n```java\n@Resource\nprivate UidGenerator uidGenerator;\n\n@Test\npublic void testSerialGenerate() {\n    // Generate UID\n    long uid = uidGenerator.getUID();\n\n    // Parse UID into [Timestamp, WorkerId, Sequence]\n    // {\"UID\":\"180363646902239241\",\"parsed\":{    \"timestamp\":\"2017-01-19 12:15:46\",    \"workerId\":\"4\",    \"sequence\":\"9\"        }}\n    System.out.println(uidGenerator.parseUID(uid));\n\n}\n```\n\n### Tips\nFor low concurrency and long term application, less ```seqBits``` but more ```timeBits``` is recommended. For\nexample, if DisposableWorkerIdAssigner is adopted and the average reboot frequency is 12 per node per day, with the\nconfiguration ```{\"workerBits\":23,\"timeBits\":31,\"seqBits\":9}```, one project can run for 68 years with 28 nodes\nand entirely concurrency 14400 UID/s.\n\nFor frequent reboot and long term application, less ```seqBits``` but more ```timeBits``` and ```workerBits``` is\nrecommended. For example, if DisposableWorkerIdAssigner is adopted and the average reboot frequency is 24 * 12 per node\nper day, with the configuration ```{\"workerBits\":27,\"timeBits\":30,\"seqBits\":6}```, one project can run for 34 years\nwith 37 nodes and entirely concurrency 2400 UID/s.\n\n#### Experiment for Throughput\nTo figure out CachedUidGenerator's UID throughput, some experiments are carried out.\u003cbr/\u003e\nFirstly, workerBits is arbitrarily fixed to 20, and change timeBits from 25(about 1 year) to 32(about 136 years),\u003cbr/\u003e\n\n|timeBits|25|26|27|28|29|30|31|32|\n|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n|throughput|6,831,465|7,007,279|6,679,625|6,499,205|6,534,971|7,617,440|6,186,930|6,364,997|\n\n![throughput1](doc/throughput1.png)\n\nThen, timeBits is arbitrarily fixed to 31, and workerBits is changed from 20(about 1 million total reboots) to 29(about\n 500 million total reboots),\u003cbr/\u003e\n\n|workerBits|20|21|22|23|24|25|26|27|28|29|\n|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n|throughput|6,186,930|6,642,727|6,581,661|6,462,726|6,774,609|6,414,906|6,806,266|6,223,617|6,438,055|6,435,549|\n\n![throughput2](doc/throughput2.png)\n\nIt is obvious that whatever the configuration is, CachedUidGenerator always has the ability to provide **6 million**\nstable throughput, what sacrificed is just life expectancy, this is very cool.\n\nFinally, both timeBits and workerBits are fixed to 31 and 23 separately, and change the number of CachedUidGenerator\nconsumer. Since our CPU only has 4 cores, \\[1, 8\\] is chosen.\u003cbr/\u003e\n\n|consumers|1|2|3|4|5|6|7|8|\n|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n|throughput|6,462,726|6,542,259|6,077,717|6,377,958|7,002,410|6,599,113|7,360,934|6,490,969|\n\n![throughput3](doc/throughput3.png)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaidu%2Fuid-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbaidu%2Fuid-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaidu%2Fuid-generator/lists"}