Skip to content
Why Snowflake IDs Change in the Browser: JavaScript's 53-bit Integer Limit

Why Snowflake IDs Change in the Browser: JavaScript's 53-bit Integer Limit

This article explains how Snowflake IDs exceeding JavaScript's MAX_SAFE_INTEGER (2^53-1) lose precision when parsed as JSON numbers, causing silent bugs like 'record not found', and recommends returning IDs as strings via Jackson's ToStringSerializer or a custom @JsonId annotation, while keeping numeric fields as numbers, aligning API contracts, OpenAPI specs, and frontend types.

LuTiao Programming
LuTiao Programming
LuTiao Programming

The Silent Precision Loss

After deploying a Snowflake ID generator, a backend service returned a task ID 1934387294876153857. The database stored it correctly, Java logs showed the same value, and the controller's Long field was intact. However, the frontend received 1934387294876153900 — the last digits changed. When the frontend called GET /api/tasks/1934387294876153900, the backend returned "not found" because that ID never existed.

Initial suspicion fell on the Snowflake algorithm, MySQL BIGINT precision, or Jackson serialization. Capturing the raw HTTP response revealed the JSON actually contained the correct number: {"id": 1934387294876153857, "name": "数据导入任务"}. The corruption happened when the browser parsed this JSON into a JavaScript object.

Java long vs JavaScript Number

Java's long is a 64-bit signed integer and easily holds Snowflake IDs. MySQL BIGINT likewise has no issue. JavaScript's Number type, however, follows IEEE 754 double-precision floating point. Its maximum safe integer is 9007199254740991 ( 2^53 - 1). MDN explicitly states that integers beyond this range are not guaranteed to be represented or compared correctly; even MAX_SAFE_INTEGER + 1 and MAX_SAFE_INTEGER + 2 may compare equal.

The Snowflake ID 1934387294876153857 far exceeds 9007199254740991. When JSON.parse(responseText) runs, the large integer enters a JavaScript Number and precision is lost. The full chain is:

MySQL BIGINT → Java Long → JSON number → JavaScript Number → precision loss

The first three steps are correct; the last step mutates the ID.

Why This Bug Is Insidious

JavaScript does not throw an overflow error. It silently produces a wrong number:

const id = 1934387294876153857;
console.log(id); // 1934387294876153900

No exception, no console error — just a mutated value. This manifests as bizarre business symptoms: "record not found" on detail views, delete requests sent with a non-existent ID, or list operations where the frontend retains the corrupted ID for subsequent mutations. Developers then waste time investigating database transactions, caches, or read replicas, while the data was already wrong the moment it entered the browser.

Best Practice: Treat Identifiers as Strings

Business IDs (task ID, order ID, user ID, message ID) are identifiers , not numbers for arithmetic. You never compute orderId + 100 or multiply user IDs. Therefore, at the API boundary they should be strings.

Change the DTO field from Long to String:

public record TaskResponse(
    String id,
    String name,
    TaskStatus status
) {}

Assemble with String.valueOf(entity.getId()). The JSON becomes {"id": "1934387294876153857", "name": "数据导入任务"}. The browser parses typeof data.id as string, eliminating any numeric conversion.

Internally, keep BIGINT in the database and Long in Java. Only at the cross-language API edge do you represent the identifier as a string — this makes the semantics clearer.

When Changing Hundreds of DTOs Is Impractical

Large legacy projects may have hundreds of Long id, Long userId, etc. A common Spring Boot approach is to configure Jackson globally:

@Bean
public Jackson2ObjectMapperBuilderCustomizer longToStringCustomizer() {
    return builder -> {
        builder.serializerByType(Long.class, ToStringSerializer.instance);
        builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
    };
}

This serializes all Long and long fields as strings. It looks like a one-time fix, but not every Long is an ID .

Global Long → String Breaks Numeric Fields

Consider a response with actual numeric values:

public record StorageUsageResponse(
    Long usedBytes,
    Long totalBytes
) {}

Global serialization would produce {"usedBytes": "104857600", "totalBytes": "1073741824"}. Frontend code like const percent = usedBytes / totalBytes * 100; may still work due to coercion, but TypeScript types, API docs, and other clients become confused. Fields like count, durationMillis, fileSize are genuine numbers that need sorting, calculation, and statistics. Converting them to strings conflates Java type with business semantics.

The real question is not "Can Long be returned to the frontend?" but "Is this Long a numeric value or an identifier ?"

Targeted Solution: Custom @JsonId Annotation

Define a dedicated annotation for ID fields:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = ToStringSerializer.class)
public @interface JsonId {}

Apply it only to identifier fields:

public class TaskResponse {
    @JsonId private Long id;
    @JsonId private Long userId;
    private Long fileSize;
    private Long durationMillis;
}

Resulting JSON:

{
  "id": "1934387294876153857",
  "userId": "1934387294876000001",
  "fileSize": 104857600,
  "durationMillis": 328
}

IDs are strings; true numeric fields remain numbers. This avoids the "why is every Long a string?" confusion and makes the API contract express business meaning.

Request Parameters Must Match

If the response uses strings, requests should too. For an update endpoint:

public record UpdateTaskRequest(
    String taskId,
    String name
) {}

Convert at the service boundary: long taskId = Long.parseLong(request.taskId()); Or introduce a value object:

public record TaskId(long value) {
    public static TaskId of(String value) {
        return new TaskId(Long.parseLong(value));
    }
    @Override public String toString() {
        return Long.toString(value);
    }
}

This makes the "external string, internal long" boundary explicit. If the codebase already uses Long in requests, a full rewrite may not be worth it — the critical rule is to never let the browser convert a large ID to Number at any stage.

URL Path Parameters: Keep as Strings

When navigating, use the string directly:

const id = row.id; // already "1934387294876153857"
router.push(`/tasks/${id}`);

Never do const id = Number(row.id) — that reintroduces precision loss. TypeScript types should declare id: string, not id: number. Once the API contract decides "large integer IDs are strings", both frontend and backend must adhere; otherwise a utility like parseInt(id) can silently revert the fix.

What About BigInt ?

JavaScript's BigInt can precisely represent large integers, and MDN recommends it for values exceeding MAX_SAFE_INTEGER. However, the ecosystem is not BigInt -native: JSON.stringify({id: 1934387294876153857n}) fails in many environments, and routers, table components, state managers, HTTP clients, and third-party SDKs often expect plain numbers or strings. Since IDs require no arithmetic, forcing BigInt throughout the frontend for a single identifier is disproportionate effort. BigInt belongs in cryptography or heavy integer math, not in identifier handling.

Excel Exports Suffer the Same Issue

If the backend exports 1934387294876153857 to Excel and Excel interprets it as a number, the same precision loss or display corruption occurs. When users copy that ID back into the system, it no longer matches. For any field that "looks like a number but is actually a string identifier" — order numbers, Snowflake IDs, ID card numbers, bank card numbers, long business codes — export as text. This is the same root cause as the JSON issue: don't treat a digit-only string as a numeric value. Phone numbers are digits too, but you don't add or subtract them; order numbers are no different.

Why Snowflake IDs Trigger This Suddenly

Snowflake IDs are typically 18–19 digits. Java long handles them effortlessly, so backend development and testing see no anomalies. Logs and direct SQL queries show correct values. The problem only surfaces when the ID reaches the browser. With auto-increment IDs (e.g., 10086, 500000, 10000000), the values stay far below MAX_SAFE_INTEGER, so the bug remains dormant. Switching to Snowflake for distributed systems suddenly crosses the 53-bit boundary, and developers mistakenly blame the algorithm. The algorithm is correct; the ID is simply entering a JavaScript Number for the first time.

Lock the Behavior with a Unit Test

Add a test to prevent regression:

@Test
void id_should_be_serialized_as_string() throws Exception {
    TaskResponse response = new TaskResponse();
    response.setId(1934387294876153857L);
    String json = objectMapper.writeValueAsString(response);
    assertThat(json).contains("\"id\":\"1934387294876153857\"");
}

Without this, a future "optimization" might remove the @JsonSerialize annotation, thinking "ID is a Long, why output a string?" Code reviews may miss it, and the next Snowflake ID that exceeds the safe integer will again cause random "not found" errors. A cheap serialization test permanently codifies the API contract.

OpenAPI / Swagger Must Declare string

If the runtime returns {"id": "1934387294876153857"} but the OpenAPI spec says:

id:
  type: integer
  format: int64

Frontend code generators will produce id: number, undoing the fix. The schema must match:

id:
  type: string
  example: "1934387294876153857"

This ensures generated TypeScript types are id: string. This is why I dislike "global Jackson magic": if the backend silently stringifies Long but the contract doesn't know, you trade one implicit bug for another implicit convention. The ideal state is code, JSON, OpenAPI, and TypeScript all agreeing on the field's type.

Layered Type Philosophy

Previously I mapped database type → Java type → JSON type → TypeScript type mechanically:

Database: BIGINT
Java: Long
JSON: number
TypeScript: number

Now I recognize each layer solves a different problem:

Database type: how to store. Java type: how to compute and represent internally. API type: what semantics are most stable for cross-system transport.

They need not be identical. For a business ID:

Database: BIGINT
Java: Long
JSON: String
TypeScript: string

This is not inconsistency; it's each layer using its most appropriate representation. The database and Java benefit from integer storage and comparison; the API boundary benefits from string fidelity.

Conclusion: A Tiny Habit Change

The fix required no database migration, no Snowflake algorithm change, no MyBatis/JPA modification. We simply established one interface rule:

All business IDs that may exceed JavaScript's safe integer range must be transmitted as strings.

Fields like userId, taskId, orderId, messageId, tenantId are treated as identifiers. Genuine numeric fields — quantities, amounts in minimal units, file sizes, durations, statistics — remain numbers.

Once this rule is set, both frontend and backend become comfortable. The mysterious "Java prints 1934387294876153857, why does frontend get 1934387294876153900?" disappears. The root cause was never Java — Java's long stores the value exactly. MySQL BIGINT stores it exactly. JSON text can represent it exactly. The hard boundary is JavaScript Number , which safely represents only up to 9007199254740991. Once a Snowflake ID crosses that line, sending it as a JSON number is gambling on whether IEEE 754 happens to represent that specific integer exactly. Business identifiers don't need to gamble; they need round-trip fidelity. For that, a string is the most accurate type.

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.

TypeScriptSpring BootAPI DesignJacksonSnowflake IDJSON SerializationIEEE 754JavaScript Number Precision
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.