baidu/uid-generator
UniqueID generator
Stale — last commit 3y ago
weakest axislast commit was 3y ago; no CI workflows detected
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
last commit was 3y ago; no CI workflows detected
- ✓3 active contributors
- ✓Apache-2.0 licensed
- ✓Tests present
Show all 7 evidence items →Show less
- ⚠Stale — last commit 3y ago
- ⚠Small team — 3 contributors active in recent commits
- ⚠Concentrated ownership — top contributor handles 60% of recent commits
- ⚠No CI workflows detected
What would change the summary?
- →Use as dependency Mixed → Healthy if: 1 commit in the last 365 days
- →Deploy as-is Mixed → Healthy if: 1 commit in the last 180 days
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Forkable" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/baidu/uid-generator)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/baidu/uid-generator on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: baidu/uid-generator
Generated by RepoPilot · 2026-05-09 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/baidu/uid-generator shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
WAIT — Stale — last commit 3y ago
- 3 active contributors
- Apache-2.0 licensed
- Tests present
- ⚠ Stale — last commit 3y ago
- ⚠ Small team — 3 contributors active in recent commits
- ⚠ Concentrated ownership — top contributor handles 60% of recent commits
- ⚠ No CI workflows detected
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live baidu/uid-generator
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/baidu/uid-generator.
What it runs against: a local clone of baidu/uid-generator — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in baidu/uid-generator | Confirms the artifact applies here, not a fork |
| 2 | License is still Apache-2.0 | Catches relicense before you depend on it |
| 3 | Default branch master exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 1103 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of baidu/uid-generator. If you don't
# have one yet, run these first:
#
# git clone https://github.com/baidu/uid-generator.git
# cd uid-generator
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of baidu/uid-generator and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "baidu/uid-generator(\\.git)?\\b" \\
&& ok "origin remote is baidu/uid-generator" \\
|| miss "origin remote is not baidu/uid-generator (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(Apache-2\\.0)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"Apache-2\\.0\"" package.json 2>/dev/null) \\
&& ok "license is Apache-2.0" \\
|| miss "license drift — was Apache-2.0 at generation time"
# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
&& ok "default branch master exists" \\
|| miss "default branch master no longer exists"
# 4. Critical files exist
test -f "src/main/java/com/baidu/fsg/uid/UidGenerator.java" \\
&& ok "src/main/java/com/baidu/fsg/uid/UidGenerator.java" \\
|| miss "missing critical file: src/main/java/com/baidu/fsg/uid/UidGenerator.java"
test -f "src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java" \\
&& ok "src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java" \\
|| miss "missing critical file: src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java"
test -f "src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java" \\
&& ok "src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java" \\
|| miss "missing critical file: src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java"
test -f "src/main/java/com/baidu/fsg/uid/buffer/RingBuffer.java" \\
&& ok "src/main/java/com/baidu/fsg/uid/buffer/RingBuffer.java" \\
|| miss "missing critical file: src/main/java/com/baidu/fsg/uid/buffer/RingBuffer.java"
test -f "src/main/java/com/baidu/fsg/uid/BitsAllocator.java" \\
&& ok "src/main/java/com/baidu/fsg/uid/BitsAllocator.java" \\
|| miss "missing critical file: src/main/java/com/baidu/fsg/uid/BitsAllocator.java"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 1103 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~1073d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/baidu/uid-generator"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
UidGenerator is a Java-based distributed unique ID generator built on the Snowflake algorithm, designed to generate over 6 million IDs per second per instance. It improves upon Twitter's Snowflake by allowing configurable bit allocation (sign/timestamp/worker ID/sequence), auto-assigning worker IDs via MySQL, and using a RingBuffer with cache-line padding to eliminate contention in high-concurrency scenarios. Single-module Maven project with layered architecture: src/main/java/com/baidu/fsg/uid/ contains core interfaces (UidGenerator, BitsAllocator), impl/ has DefaultUidGenerator and CachedUidGenerator implementations, buffer/ manages the RingBuffer producer-consumer pattern, worker/ handles WorkerID assignment and persistence via DAO, utils/ provides threading, networking, and Docker utilities, and resources/ includes MyBatis mapper XML for worker node persistence.
👥Who it's for
Backend engineers at Baidu and other large-scale distributed systems who need to generate unique IDs across multiple service instances in virtualized environments (Docker/Kubernetes), replacing database auto-increment sequences or UUID generation with low-latency, high-throughput alternatives.
🌱Maturity & risk
Mature and production-ready. The codebase is well-structured with clear separation of concerns (buffer, worker, utils modules), includes comprehensive documentation with architecture diagrams (ringbuffer.png, snowflake.png, cacheline_padding.png, throughput benchmarks), and demonstrates performance optimization techniques. However, the 1.0.0-SNAPSHOT version string and sparse test directory suggest it may lack extensive test coverage.
Low to moderate risk. The codebase has minimal external dependencies (Spring 4.2.5, MyBatis 3.2.3, SLF4J 1.7.7) and the core algorithm is proven (Snowflake-based). Main risks: hard dependency on MySQL for the default WorkerNodeDAO implementation (though pluggable), Java 8+ requirement, and dated Spring/MyBatis versions (from ~2016) that may have unpatched security issues if used in production without upgrades.
Active areas of work
No recent commit information is visible from the provided data, but the repo appears stable/dormant rather than actively developed. The 1.0.0-SNAPSHOT version suggests work was halted before a stable release, and the dated Spring versions indicate no recent dependency updates.
🚀Get running
Clone, build, and optionally configure: git clone https://github.com/baidu/uid-generator.git && cd uid-generator && mvn clean install. For MySQL-based worker ID assignment, create the WORKER_NODE table using src/main/scripts/WORKER_NODE.sql and configure Spring datasource beans. For testing, examine the test directory structure under src/test/java.
Daily commands:
mvn clean install compiles and packages the library. No runnable main class is present; this is a component library consumed by other Spring applications. Integration: instantiate CachedUidGenerator or DefaultUidGenerator as a Spring bean (with @Bean factory method), provide a WorkerIdAssigner implementation (or use the built-in DisposableWorkerIdAssigner with MySQL), then call generator.getUID() to obtain IDs.
🗺️Map of the codebase
src/main/java/com/baidu/fsg/uid/UidGenerator.java— Core interface defining the contract for UID generation; all implementations must conform to this abstract specification.src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java— Reference implementation of Snowflake algorithm; foundational for understanding the core UID generation logic and bit allocation strategy.src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java— High-performance variant using RingBuffer caching; critical for achieving 6M+ QPS throughput with background padding threads.src/main/java/com/baidu/fsg/uid/buffer/RingBuffer.java— Lock-free concurrent data structure enabling parallel production/consumption of UIDs with padding to eliminate cache-line contention.src/main/java/com/baidu/fsg/uid/BitsAllocator.java— Encapsulates bit layout configuration (timestamp, worker ID, sequence); essential for customizing UID structure per deployment requirements.src/main/java/com/baidu/fsg/uid/worker/dao/WorkerNodeDAO.java— Database abstraction for persistent worker ID assignment; required for distributed deployment and preventing ID collisions across instances.src/main/resources/META-INF/mybatis/mapper/WORKER_NODE.xml— MyBatis mapper defining worker node persistence layer; critical for multi-instance deployments to assign unique worker IDs.
🛠️How to make changes
Implement a custom WorkerIdAssigner for non-database environments
- Extend the WorkerIdAssigner interface in a new class (e.g., StaticWorkerIdAssigner.java) in src/main/java/com/baidu/fsg/uid/worker/ (
src/main/java/com/baidu/fsg/uid/worker/WorkerIdAssigner.java) - Implement assignWorkerId() to return a static or computed worker ID without database access (
src/main/java/com/baidu/fsg/uid/worker/WorkerIdAssigner.java) - Inject your custom assigner into DefaultUidGenerator or CachedUidGenerator via constructor in Spring configuration (
src/test/resources/uid/default-uid-spring.xml) - Add unit tests in src/test/java/com/baidu/fsg/uid/ following the DefaultUidGeneratorTest pattern (
src/test/java/com/baidu/fsg/uid/DefaultUidGeneratorTest.java)
Customize bit allocation (e.g., increase sequence bits, reduce timestamp range)
- Create a BitsAllocator instance with desired bit widths (timestampBits, workerIdBits, sequenceBits) in your configuration (
src/main/java/com/baidu/fsg/uid/BitsAllocator.java) - Pass the custom BitsAllocator to DefaultUidGenerator constructor to override defaults (
src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java) - Verify bit allocation is valid (total ≤ 63 bits) in BitsAllocator validation logic (
src/main/java/com/baidu/fsg/uid/BitsAllocator.java) - Update Spring XML configuration (default-uid-spring.xml) to pass custom BitsAllocator as property (
src/test/resources/uid/default-uid-spring.xml)
Switch from DefaultUidGenerator to CachedUidGenerator for high-throughput deployments
- Replace bean class from DefaultUidGenerator to CachedUidGenerator in Spring configuration (
src/test/resources/uid/cached-uid-spring.xml) - Configure RingBuffer capacity and padding threads via CachedUidGenerator properties (e.g., ringSize, boostPower) (
src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java) - Set rejection handlers for put/take buffer operations if queue is full via RejectedPutBufferHandler or RejectedTakeBufferHandler (
src/main/java/com/baidu/fsg/uid/buffer/RejectedPutBufferHandler.java) - Monitor BufferPaddingExecutor thread metrics to validate padding thread efficiency (
src/main/java/com/baidu/fsg/uid/buffer/BufferPaddingExecutor.java)
Deploy across multiple instances with persistent worker ID assignment
- Create WORKER_NODE table in MySQL using the provided DDL script (
src/main/scripts/WORKER_NODE.sql) - Configure MyBatis datasource in Spring XML pointing to the MySQL instance (
src/test/resources/uid/mybatis-spring.xml) - Use DisposableWorkerIdAssigner (which queries WORKER_NODE table) in your Spring bean definition (
src/main/java/com/baidu/fsg/uid/worker/DisposableWorkerIdAssigner.java) - Each application instance will auto-register and claim a unique worker ID on first initialization (
src/main/java/com/baidu/fsg/uid/worker/dao/WorkerNodeDAO.java)
🪤Traps & gotchas
RingBuffer size must be a power of 2 (validated implicitly via boostPower configuration). MySQL must be running and reachable if using the default DisposableWorkerIdAssigner; no fallback is provided in the base codebase. The sequence bits are re-used per second (clock reset detection exists but edge cases may occur during clock skew). Spring 4 XML configuration is assumed; no Spring Boot auto-configuration is present. Worker node IDs are disposed after reboot, so rapid restarts can exhaust the 22-bit ID space (4.2M max).
🏗️Architecture
💡Concepts to learn
- Snowflake Algorithm — UidGenerator's foundation; understanding its 64-bit composition (sign, timestamp delta, worker ID, sequence) is essential for configuring BitsAllocator and designing ID spaces for your domain.
- Lock-Free RingBuffer / Producer-Consumer Queue — The core concurrency pattern in CachedUidGenerator; achieves 6M QPS by decoupling UID production from consumption without locks, critical for understanding why this generator outperforms DefaultUidGenerator.
- Cache-Line Padding / False Sharing — PaddedAtomicLong prevents CPU cache line contention between threads; this subtle optimization is why UidGenerator achieves such high throughput and is a key insight for understanding modern concurrent Java design.
- Bits Allocation / Configurable Field Widths — UidGenerator allows trading off between timestamp precision, worker ID count, and sequence space; understanding this trade-off is essential when deploying across different scales (few large workers vs. many small instances).
- Distributed Worker ID Assignment — DisposableWorkerIdAssigner uses MySQL to coordinate unique worker IDs across instances; this pattern is fundamental for preventing collisions in distributed systems and handling node churn in Docker/Kubernetes.
- Monotonic Increasing IDs with Clock Skew Handling — UidGenerator detects clock resets and adjusts sequence counters; critical for understanding potential edge cases when system clocks are synced or VMs migrate in virtualized environments.
- MyBatis DAO Pattern — WorkerNodeDAO and the WORKER_NODE.xml mapper demonstrate how UidGenerator persists and retrieves worker node metadata; understanding this is necessary to swap in alternative persistence backends (Redis, Etcd, etc.).
🔗Related repos
twitter/snowflake— The original Snowflake distributed ID generator that UidGenerator is based on; provides the algorithmic foundation.sony/sonyflake— Alternative to Snowflake written in Go with similar distributed ID guarantees; useful for understanding how other ecosystems solve the same problem.apache/dubbo— Baidu's distributed RPC framework which likely consumes UidGenerator for service-to-service unique request/transaction IDs in production.seata/seata— Distributed transaction framework that may depend on UidGenerator for generating globally unique transaction IDs across services.google/uuid— Standard UUID library; provides context for why high-throughput alternatives like UidGenerator are needed (UUID performance vs. sequential ID predictability).
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive unit tests for WorkerIdAssigner implementations and Docker utilities
The test directory lacks coverage for critical worker ID assignment logic (DisposableWorkerIdAssigner, WorkerNodeDAO integration) and Docker-specific utilities (DockerUtils.java). These are essential for virtualization environments which the README highlights as a key use case. Missing tests here could lead to deployment failures in containerized environments.
- [ ] Create src/test/java/com/baidu/fsg/uid/worker/DisposableWorkerIdAssignerTest.java to test WorkerNode entity creation and database persistence
- [ ] Create src/test/java/com/baidu/fsg/uid/utils/DockerUtilsTest.java to test Docker environment detection and container ID extraction logic
- [ ] Add integration tests in src/test/java/com/baidu/fsg/uid/worker/dao/WorkerNodeDAOTest.java to validate DAO operations against test database configured in mysql.properties
Add unit tests for RingBuffer and buffer rejection handlers
The RingBuffer (src/main/java/com/baidu/fsg/uid/buffer/RingBuffer.java) is critical to the caching strategy mentioned in the README for achieving 6M+ QPS. The rejection handlers (RejectedPutBufferHandler, RejectedTakeBufferHandler) handle edge cases but have no test coverage. This risks concurrency bugs and performance degradation.
- [ ] Create src/test/java/com/baidu/fsg/uid/buffer/RingBufferTest.java testing put/take operations, buffer overflow scenarios, and concurrent access patterns
- [ ] Create src/test/java/com/baidu/fsg/uid/buffer/RejectedPutBufferHandlerTest.java and RejectedTakeBufferHandlerTest.java to verify rejection policies under contention
- [ ] Add stress test methods in CachedUidGeneratorTest.java validating CacheLine padding effectiveness using PaddedAtomicLong
Add CI/CD workflow for MySQL-dependent integration tests and performance benchmarking
The project depends on MySQL for WorkerNode management but lacks automated testing infrastructure. There's no GitHub Actions workflow to validate that schema changes in src/main/scripts/WORKER_NODE.sql work correctly, and performance benchmarks (referenced in doc/throughput*.png) are manual. Adding CI would prevent regressions and track performance over time.
- [ ] Create .github/workflows/integration-tests.yml to spin up MySQL container, execute src/main/scripts/WORKER_NODE.sql, and run integration test suite against real database
- [ ] Create .github/workflows/performance-benchmark.yml to run DefaultUidGeneratorTest and CachedUidGeneratorTest with JMH benchmarks, comparing throughput against baseline thresholds mentioned in README (6M QPS)
- [ ] Document benchmark results in doc/PERFORMANCE.md with comparison to doc/throughput*.png baselines, including setup instructions
🌿Good first issues
- Add integration tests in src/test/java/ covering CachedUidGenerator end-to-end with an embedded H2 database (or testcontainers MySQL) to verify the RingBuffer behavior under high concurrency; the test directory is sparse and lacks concrete scenarios.
- Document the CachedUidGenerator configuration properties (boostPower, rejectedPutBufferHandler, rejectedTakeBufferHandler, paddingFactor) with code examples in a dedicated CONFIGURATION.md file, since the README only covers the Snowflake algorithm.
- Implement a pluggable WorkerIdAssigner alternative using environment variables (WORKER_ID, DATACENTER_ID) or Docker container labels, eliminating the MySQL dependency for containerized deployments; add a DockerEnvWorkerIdAssigner class alongside DisposableWorkerIdAssigner.
⭐Top contributors
Click to expand
Top contributors
- @baozhi — 3 commits
- @appdesignx — 1 commits
- @gaoxiaoliang — 1 commits
📝Recent commits
Click to expand
Recent commits
🔒Security observations
- High · Outdated Spring Framework Dependencies —
pom.xml - spring-core, spring-beans, spring-context, spring-jdbc dependencies. The project uses Spring Framework version 4.2.5.RELEASE (released 2016), which contains multiple known security vulnerabilities including CVE-2018-1272, CVE-2018-1258, and others. This version is over 8 years old and no longer receives security updates. Fix: Upgrade to Spring Framework 5.3.x or 6.0.x (latest stable versions). Perform thorough compatibility testing with the application after upgrade. - High · Outdated MyBatis Dependencies —
pom.xml - mybatis and mybatis-spring dependencies. MyBatis version 3.2.3 (released 2013) and mybatis-spring 1.2.4 (released 2014) are extremely outdated and contain known security vulnerabilities. These versions lack important security patches and bug fixes. Fix: Upgrade to MyBatis 3.5.x+ and mybatis-spring 2.0.x+. Review and test SQL mapper configurations for injection vulnerabilities after upgrade. - High · Outdated SLF4J Dependency —
pom.xml - slf4j-version property set to 1.7.7. SLF4J version 1.7.7 (released 2014) is outdated and may have known security issues. Current versions provide better security and performance. Fix: Upgrade SLF4J to version 2.0.x or latest 1.7.x patch version (1.7.36+). Update all dependent logging implementations (Logback, Log4j2) accordingly. - Medium · Potential SQL Injection via MyBatis Mapper —
src/main/resources/META-INF/mybatis/mapper/WORKER_NODE.xml and src/main/java/com/baidu/fsg/uid/worker/dao/WorkerNodeDAO.java. The presence of WORKER_NODE.xml MyBatis mapper and WorkerNodeDAO suggests dynamic SQL queries. Without examining the mapper content, there's risk of SQL injection if user input is improperly parameterized. Fix: Ensure all SQL queries use parameterized queries/prepared statements. Avoid string concatenation for SQL query building. Use MyBatis placeholders (#{}) instead of ${} for user input. - Medium · Missing Dependency Version Management —
pom.xml - dependencies section. The pom.xml lacks explicit version declarations for transitive dependencies and does not use a dependencyManagement section. This can lead to unpredictable versions of vulnerable libraries being pulled in. Fix: Add a <dependencyManagement> section to explicitly manage all dependency versions. Use Maven Dependency Plugin to verify the actual dependency tree and identify any vulnerable transitive dependencies. - Medium · Hardcoded Database Configuration Reference —
src/test/resources/uid/mysql.properties. The presence of mysql.properties in test resources suggests potential hardcoded database credentials. Configuration files should never contain plaintext credentials. Fix: Remove credentials from mysql.properties. Use environment variables or secure configuration management systems (Spring Cloud Config, HashiCorp Vault, AWS Secrets Manager) for sensitive configuration. - Low · Java 8 Minimum Version Specification —
pom.xml - jdk.version property. The project targets Java 8 (jdk.version=1.8), which reached end of life for most distributions. While the code may run on newer Java versions, explicit support for modern versions should be declared. Fix: Update target Java version to at least Java 11 or Java 17 (LTS). Test application thoroughly with newer Java versions and update source/target compilation settings accordingly. - Low · Missing Maven Security Plugin Configuration —
pom.xml - build configuration section. The pom.xml does not include any security scanning plugins (dependency-check, OWASP plugin) to automatically detect known vulnerabilities during build time. Fix: Add OWASP Dependency-Check plugin or Maven Enforcer plugin to the build lifecycle to fail builds on vulnerable dependencies. Configure regular dependency updates and security scanning.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.