Generate unique number with number of digits between 10 and 16

Noah Aas 985 Reputation points
2025-04-13T14:03:47.89+00:00

Hello,

I have a client server application.

I have to send a message identification number. What options do I have to generate a unique number?

The number of digits should be between 10 and 16. It must be ensured that no duplicate numbers are generated during runtime.

Many thanks for the good and helpful tips.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 50,735 Reputation points MVP Volunteer Moderator
    2025-04-13T14:59:17.42+00:00

    Here are a few options to consider:

    1. Atomic counter (single process) A simple, thread-safe counter starting from the current time in milliseconds.
    private static long _messageIdCounter = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    
    public static long GetNextMessageId()
    {
        return Interlocked.Increment(ref _messageIdCounter);
    }
    
    • Produces 13-digit numbers.
    • Unique within the current process runtime.
    • Not safe across multiple processes or restarts.
    1. Timestamp with random suffix (safe for distributed systems) Combines current time with a random number to reduce the chance of collisions.
    public static long GenerateMessageId()
    {
        long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // 13 digits
        int random = RandomNumberGenerator.GetInt32(0, 100); // 2-digit random number
        return long.Parse($"{timestamp}{random:D2}");
    }
    
    • Results in 15-digit numbers.
    • Very low probability of collision, even across systems.
    1. GUID to numeric conversion Use a GUID and convert it to a long, then use modulo to limit the number to a maximum of 16 digits.
    public static long GenerateNumericFromGuid()
    {
        Guid guid = Guid.NewGuid();
        byte[] bytes = guid.ToByteArray();
        long raw = BitConverter.ToInt64(bytes, 0);
        
        // Ensure it's positive and within 16 digits
        return Math.Abs(raw % 1_000_000_000_000_0000); // max 16 digits
    }
    
    • While GUIDs have very high uniqueness, using modulo slightly reduces that guarantee.
    • Still safe for most practical applications.

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.