How to Build a Scalable, Unique Invitation Code System in Java

This article explains the requirements for invitation codes, critiques simple random generation, and presents a custom base‑32 encoding method in Java that guarantees uniqueness, efficiency, and reversibility while allowing easy expansion.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
How to Build a Scalable, Unique Invitation Code System in Java

Invitation codes are widely used in app promotion to reward users who invite others, so a robust generation mechanism must ensure global uniqueness, randomness, efficiency, and user‑friendly length (typically six characters of digits and uppercase letters).

Characteristics of a Good Invitation Code

Uniqueness – each code must be distinct to identify the inviter and enable reverse lookup.

Randomness – the generation rule should not be easily inferred.

Efficiency – the algorithm should be lightweight and not consume excessive resources.

Simplicity – codes should be easy to type, store, and validate.

Common formats are pure numeric or alphanumeric strings of about six characters.

Why Simple Random Generation Fails

Generating a six‑digit random number (000000‑999999) yields one million possibilities. With 500,000 users, the collision probability exceeds 50%, leading to severe performance overhead from repeated retries. Pre‑generating codes in a database or Redis reduces collisions but still consumes storage and time.

Custom Base‑32 Encoding Approach

Inspired by Base64, the solution maps a user’s long integer ID to a six‑character code using a custom 32‑character alphabet (digits 2‑9 and selected uppercase letters, excluding 0, 1, O, I to avoid confusion). This provides 32⁶ ≈ 1.07 billion unique codes.

6位邀请码:0‑9十个数字,26个大写字母,在这其中再去除掉0和1,O和I防止它们两两混淆。

The algorithm converts the ID to base‑32, appends a fixed separator character ‘A’, and then randomly fills any remaining positions to reach the required length.

public class ShareCodeUtils {
    private static final char[] BASE = {'H','V','E','8','S','2','D','Z','X','9','C','7','P','5','I','K','3','M','J','U','F','R','4','W','Y','L','T','N','6','B','G','Q'};
    private static final char SUFFIX_CHAR = 'A';
    private static final int BIN_LEN = BASE.length;
    private static final int CODE_LEN = 6;

    public static String idToCode(Long id) {
        char[] buf = new char[BIN_LEN];
        int charPos = BIN_LEN;
        while (id / BIN_LEN > 0) {
            int index = (int)(id % BIN_LEN);
            buf[--charPos] = BASE[index];
            id /= BIN_LEN;
        }
        buf[--charPos] = BASE[(int)(id % BIN_LEN)];
        String result = new String(buf, charPos, BIN_LEN - charPos);
        if (result.length() < CODE_LEN) {
            StringBuilder sb = new StringBuilder();
            sb.append(SUFFIX_CHAR);
            Random random = new Random();
            for (int i = 0; i < CODE_LEN - result.length() - 1; i++) {
                sb.append(BASE[random.nextInt(BIN_LEN)]);
            }
            result += sb.toString();
        }
        return result;
    }

    public static Long codeToId(String code) {
        char[] charArray = code.toCharArray();
        long result = 0L;
        for (int i = 0; i < charArray.length; i++) {
            int index = 0;
            for (int j = 0; j < BIN_LEN; j++) {
                if (charArray[i] == BASE[j]) { index = j; break; }
            }
            if (charArray[i] == SUFFIX_CHAR) break;
            result = i > 0 ? result * BIN_LEN + index : index;
        }
        return result;
    }

    public static void main(String[] args) {
        String code = idToCode(1L);
        System.out.println(code);
        System.out.println(codeToId(code));
    }
}

This method guarantees that each user ID maps to a unique six‑character code and that the code can be reversed to retrieve the original ID.

Enhancements and Scaling

Shuffle the BASE array to increase apparent randomness.

Introduce salting or position swapping for higher complexity while preserving uniqueness.

When the 1 billion‑code space becomes insufficient, extend the code length (e.g., to 7 or 8 characters) or enlarge the alphabet by adding lowercase letters.

The source code is available on GitHub for download.

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.

BackendJavaScalabilityunique identifierBase32 EncodingInvitation Code
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

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.