denoland/deno · error · RangeError

Value must fit in a 64-bit unsigned integer

Error message

Value must fit in a 64-bit unsigned integer

What it means

KvU64 must fit the unsigned 64-bit range; a bigint above 0xffffffffffffffff (2^64 - 1, MAX_U64 in the source) throws RangeError('Value must fit in a 64-bit unsigned integer'). Overflow is rejected rather than wrapped because silent wrapping would corrupt counters.

Solutions

  1. Bound-check before the mutation: value <= 0xffff_ffff_ffff_ffffn.
  2. Re-model big magnitudes: store as bytes, split into hi/lo counters, or track in multiple keys.
  3. Scale units down (store milliseconds instead of nanoseconds, whole tokens instead of base units) so sums stay in range.

Example fix

// before
await kv.atomic().sum(["volume"], weiAmount).commit(); // may exceed 2^64-1

// after
const MAX_U64 = 0xffffffffffffffffn;
if (weiAmount > MAX_U64) throw new RangeError("amount exceeds u64");
await kv.atomic().sum(["volume"], weiAmount).commit();
Defensive patterns

Strategy: validation

Validate before calling

const MAX_U64 = 0xffffffffffffffffn;
function assertU64(v: bigint) {
  if (v > MAX_U64) throw new RangeError(`value exceeds 64-bit unsigned range: ${v}`);
  if (v < 0n) throw new RangeError(`value must be unsigned: ${v}`);
}
assertU64(total);
await kv.atomic().sum(key, total).commit();

Type guard

const fitsU64 = (v: bigint): boolean => v >= 0n && v <= 0xffffffffffffffffn;

Prevention

When it happens

Trigger: `.sum(key, 2n ** 64n)`; accumulated products (price * quantity) exceeding 2^64; bit math like 1n << 64n; importing 128-bit identifiers or hashes as counters.

Common situations: Aggregations over huge magnitudes (wei/gwei token amounts, nanosecond timestamps multiplied by counts); migrating 128-bit values from other stores into Kv counters.

Related errors


AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20). Data as JSON: /api/errors/1af1468eb2d77fca. Report an issue: GitHub.

Appendix: source

Thrown at ext/kv/01_db.ts:740

}

const MIN_U64 = BigInt("0");
const MAX_U64 = BigInt("0xffffffffffffffff");

class KvU64 {
  value: bigint;

  constructor(value: bigint) {
    if (typeof value !== "bigint") {
      throw new TypeError(`Value must be a bigint: received ${typeof value}`);
    }
    if (value < MIN_U64) {
      throw new RangeError(
        `Value must be a positive bigint: received ${value}`,
      );
    }
    if (value > MAX_U64) {
      throw new RangeError("Value must fit in a 64-bit unsigned integer");
    }
    this.value = value;
    ObjectFreeze(this);
  }

  valueOf() {
    return this.value;
  }

  toString() {
    return BigIntPrototypeToString(this.value);
  }

  get [SymbolToStringTag]() {
    return "Deno.KvU64";
  }

  [SymbolFor("Deno.privateCustomInspect")](inspect, inspectOptions) {

View on GitHub (pinned to 9ad36f7a2c)