# db — Database ID Generation > `import { newId } from 'puffy-core/db'` > CJS: `const { db: { newId } } = require('puffy-core')` > Also available in snake_case: `new_id` --- ## newId Generates a monotonically increasing BigInt suitable for use as a database primary key. The ID is random but grows with time, so it can be used for both uniqueness and chronological sorting. ### Signature ``` newId(options?: { timestamp?: Date, node?: number, idx?: number }) → BigInt ``` Parameters: - `timestamp` (Date, default: `new Date()`): Base timestamp for the ID - `node` (number, default: 0): Node identifier, range 0–99. Use for distributed systems where multiple machines generate IDs. - `idx` (number, default: random 0–9999): Sequence index within the same millisecond Returns: BigInt ### ID structure ``` 1737111960607 00 2926 └──────┬─────┘ └┬┘ └─┬─┘ epoch ms node random idx (13 digits) (2) (4 digits) ``` ### Examples ```js newId() // 1737111960607002926n newId({ node:18 }) // 1737111960611181693n — node=18 embedded in the ID newId({ node:18, idx:9999 }) // 1737111960611189999n — fixed idx for testing newId({ timestamp:new Date('1985-03-21') }) // 480211200000003307n — historical timestamp ``` ### Options table | Option | Type | Default | Range | Description | |---|---|---|---|---| | `timestamp` | Date | `new Date()` | — | Base timestamp | | `node` | number | `0` | 0–99 | Node identifier for distributed systems | | `idx` | number | random | 0–9999 | Sequence index within same millisecond | GOTCHA: `newId()` returns a **BigInt**, not a number or string. Standard `JSON.stringify` throws on BigInt values. Use `safeStringify` from `puffy-core/string`: ```js import { newId } from 'puffy-core/db' import { safeStringify } from 'puffy-core/string' const id = newId() JSON.stringify({ id }) // TypeError: Do not know how to serialize a BigInt safeStringify({ id }) // '{"id":"1737111960607002926"}' // To convert to string for APIs or databases: id.toString() // '1737111960607002926' ``` GOTCHA: When storing in a database, use a `BIGINT` column type or store as a string. JavaScript `Number` cannot safely represent integers larger than `Number.MAX_SAFE_INTEGER` (2^53 - 1), and these IDs exceed that limit.