Choosing the Right Distributed ID Strategy for Spring Boot: A Complete Guide

Generating globally unique, ordered, high‑performance IDs is essential for distributed systems, and this guide compares common ID schemes, outlines key selection criteria, and provides step‑by‑step Spring Boot integration examples using Baidu UidGenerator, CosId, and Snowflake, along with configuration, code, and best‑practice recommendations.

Ray's Galactic Tech
Ray's Galactic Tech
Ray's Galactic Tech
Choosing the Right Distributed ID Strategy for Spring Boot: A Complete Guide

Why Distributed ID Generation Matters

Generating globally unique, ordered, high‑performance IDs is a foundational capability for distributed systems such as database sharding, micro‑service tracing, and log chain tracking.

Common ID Schemes Comparison

UUID : globally unique, no ordering, high throughput (~3.07M/s), fully autonomous, 128‑bit storage.

Snowflake (and variants) : globally unique, time‑ordered, medium throughput (~4.09M/s), depends on clock stability, 64‑bit storage.

Segment : globally unique, time‑ordered, high throughput (~29.5M/s), requires DB/Redis for worker‑ID allocation, 64‑bit storage.

SegmentChain : globally unique, time‑ordered, extremely high throughput (~127M/s), similar dependencies, 64‑bit storage, supports dynamic scaling.

Key Selection Criteria

Global Uniqueness – non‑negotiable for all scenarios.

Ordering – increasing IDs improve database index performance.

Throughput – higher QPS and low tail latency are preferred.

Stability – the solution must stay stable under high load.

Autonomy & Availability – minimal reliance on external components.

Adaptability – ability to scale with traffic spikes.

Storage Size – 64‑bit integers reduce storage and index overhead.

Spring Boot Integration Options

1. Use an existing starter (quick start)

Example with Baidu UidGenerator:

<dependency>
    <groupId>cc.siyecao.uid</groupId>
    <artifactId>uid-spring-boot-starter</artifactId>
    <version>latest</version>
</dependency>
<dependency>
    <groupId>cc.siyecao.uid</groupId>
    <artifactId>uid-database</artifactId>
    <version>latest</version>
</dependency>

Configuration (application.yml):

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC
    username: your_username
    password: your_password

uid-generator:
  assigner-mode: db   # workerId allocation mode: db, zk, redis, none
  time-bits: 30
  worker-bits: 22
  seq-bits: 11
  epoch-str: "2016-05-20"

Database table for worker nodes:

CREATE TABLE WORKER_NODE (
  ID BIGINT NOT NULL AUTO_INCREMENT,
  HOST_NAME VARCHAR(64) NOT NULL,
  PORT VARCHAR(64) NOT NULL,
  TYPE INT NOT NULL COMMENT 'ACTUAL or CONTAINER',
  LAUNCH_DATE DATE NOT NULL,
  MODIFIED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (ID)
) ENGINE=InnoDB;

Usage in a service:

@Service
public class MyService {
    @Autowired
    private UidGenerator uidGenerator;

    public long generateId() {
        return uidGenerator.getUID();
    }
}

2. Manual configuration for flexibility

Example with CosId:

<dependency>
    <groupId>me.ahoo.cosid</groupId>
    <artifactId>cosid-spring-boot-starter</artifactId>
    <version>latest</version>
</dependency>

Configuration (application.yml):

spring:
  redis:
    host: localhost
    port: 6379

cosid:
  namespace: my-app
  segment:
    enabled: true
    distributor:
      type: redis
  snowflake:
    enabled: true
    clock-backwards:
      spin-threshold: 10

Controller exposing IDs:

@RestController
public class IdController {

    private final SnowflakeId snowflakeId;
    private final SegmentId segmentId;

    public IdController(SnowflakeId snowflakeId, SegmentId segmentId) {
        this.snowflakeId = snowflakeId;
        this.segmentId = segmentId;
    }

    @GetMapping("/snowflake-id")
    public long snowflake() {
        return snowflakeId.generate();
    }

    @GetMapping("/segment-id")
    public long segment() {
        return segmentId.generate();
    }
}

Selection Recommendations

Performance‑first : SegmentChain > Segment > Snowflake > UUID.

Simple autonomy : UUID for tiny projects.

Balanced choice : Snowflake when you need good performance with moderate autonomy, handling clock‑backward scenarios.

Scalable flexibility : CosId, which supports multiple modes and eases future migrations.

Practical Tips

Clock rollback is the biggest risk for Snowflake; implement spin‑wait or reject strategies.

Ensure each instance gets a unique worker ID, typically via DB, Redis, or ZooKeeper.

Segment‑based solutions depend heavily on a reliable segment distributor; plan for high availability.

Monitor ID generation latency, failure rates, and health of the segment distributor.

Conclusion

For small projects, UUID suffices. Medium traffic can use Snowflake for a balance of performance and autonomy. High‑concurrency, large‑scale systems benefit from Segment or SegmentChain, with CosId offering a one‑stop framework that simplifies future switching.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendsnowflakedistributed-idspring-bootcosid
Ray's Galactic Tech
Written by

Ray's Galactic Tech

Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.