惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
Hacker News: Ask HN
Hacker News: Ask HN
Know Your Adversary
Know Your Adversary
C
Cisco Blogs
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
T
Tor Project blog
T
Tenable Blog
P
Privacy & Cybersecurity Law Blog
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
腾讯CDC
L
LangChain Blog
IT之家
IT之家
Recent Commits to openclaw:main
Recent Commits to openclaw:main
月光博客
月光博客
N
News and Events Feed by Topic
GbyAI
GbyAI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tailwind CSS Blog
Jina AI
Jina AI
S
Security Affairs
T
The Blog of Author Tim Ferriss
博客园 - Franky
H
Hacker News: Front Page
Martin Fowler
Martin Fowler
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
Webroot Blog
Webroot Blog
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
U
Unit 42
S
Schneier on Security
B
Blog
Schneier on Security
Schneier on Security
Latest news
Latest news
TaoSecurity Blog
TaoSecurity Blog
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
Recorded Future
Recorded Future
O
OpenAI News
雷峰网
雷峰网
H
Heimdal Security Blog

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
UUIDv7 vs ULID: Sortable Identifiers That Do Not Destroy Your Write Performance
The Practica · 2026-05-20 · via The Practical Developer

Your user table is hitting 50,000 inserts per minute and the write latency graph looks like a heartbeat monitor during a panic attack. The query planner says the primary key index is 80% of the table size. Autovacuum cannot keep up. The on-call rotation is debating whether to page the DBA or just turn off the monitoring.

The cause is almost always the same: you are using UUIDv4 as a primary key, and every insert is landing in a random leaf page of your B-tree index. Postgres (or MySQL, or SQL Server) has to split pages, rebalance the tree, and flush dirty buffers all over the disk. The index grows fat with dead space. Writes that should be sequential appends become random I/O storms.

The fix is not “switch to bigserial.” Distributed systems still need decentralized ID generation. The fix is using a sortable identifier: one that carries time at the front, so inserts cluster near the end of the index where they belong. The two practical options today are UUIDv7 (RFC 9562, standardized May 2024) and ULID. Both give you time-ordered IDs without a central coordinator. Both beat UUIDv4 for write throughput. But they differ in encoding, storage size, collision resistance within a millisecond, and how much your ORM fights you.

This post walks through the B-tree mechanics that make UUIDv4 painful, compares UUIDv7 and ULID head-to-head, and ships working Node.js code you can drop into a service today.

Why random IDs murder write performance

A B-tree index stores keys in sorted order. If your primary key is a bigserial (1, 2, 3, …), every new insert appends to the rightmost leaf page. Postgres keeps that page hot in memory. Writes are cheap, sequential, and predictable.

If your primary key is a UUIDv4, the key space is effectively random. Insert 1 lands at leaf 47. Insert 2 lands at leaf 12,003. Insert 3 lands at leaf 892. The buffer cache is constantly evicting pages to make room for new ones. When a leaf page fills up, Postgres splits it: half the keys move to a new page, the parent page gets updated, and WAL is generated for every touched block. On a busy write workload, this is called an “insertion hotspot” only in the sense that the entire index becomes a hotspot.

You can see it in pgstattuple:

SELECT pg_size_pretty(pg_relation_size('users_pkey')) AS index_size,
       avg_leaf_density,
       leaf_fragmentation
FROM pgstatindex('users_pkey');

A UUIDv4 primary key on a high-insert table often shows leaf_fragmentation above 40% and avg_leaf_density below 60%. That means nearly half your index pages are half-empty, and the index is 1.5-2x larger than it needs to be. Every index scan reads more blocks. Every write waits on more locks. Your SSD is doing random I/O for a workload that should be append-only.

Sortable IDs fix this by making the key monotonically increasing over time. The first 48 bits encode a Unix millisecond timestamp. Inserts from the same millisecond cluster near each other, and inserts from the next millisecond cluster slightly to the right. The index becomes append-mostly. Page splits drop. Buffer cache efficiency rises. The DBA sleeps through the night.

UUIDv7: what changed and why it matters

UUIDv7 is part of RFC 9562, finalized in 2024. It replaces the UUIDv1 timestamp strategy (which leaked MAC addresses and had weird bit-shuffling) with something actually usable.

The 128-bit layout is clean:

  • Bits 0-47: Unix timestamp in milliseconds, big-endian.
  • Bits 48-51: version field (set to 0111, i.e., 7).
  • Bits 52-63: 12 random bits (the “rand_a” field).
  • Bits 64-65: variant field (10).
  • Bits 66-127: 62 random bits (the “rand_b” field).

Because the timestamp is at the very front in big-endian, the raw 16-byte binary representation sorts lexicographically by time. Postgres stores uuid columns as 16-byte binary. A UUIDv7 stored in a uuid column naturally sorts from oldest to newest without any special functions or index tricks.

Node.js 22.7.0 and later support UUIDv7 directly in the standard library:

import { randomUUID } from 'node:crypto';

// Node.js 22.7+
const id = randomUUID({ version: 7 });
// => 018ff4a0-... (starts with a timestamp prefix)

If you are on an older Node.js version, the uuid package (v10+) supports v7:

import { v7 as uuidv7 } from 'uuid';

const id = uuidv7(); // returns a string like 018ff4a0-...

Both outputs are RFC-compliant and safe to store in Postgres uuid columns.

One subtle advantage of UUIDv7: because the timestamp is millisecond-precision and the remaining 74 bits are random, you get about 1.9e22 possible values per millisecond. In practice, collisions are impossible without a broken RNG. But if you are generating thousands of IDs inside the exact same millisecond from a single process, the random suffix is flat. Some UUIDv7 implementations (including the Node.js one) use a monotonic random counter when multiple IDs are requested within the same millisecond, guaranteeing strict ordering even inside a single tick. That matters if your code batches inserts and assumes the generated array is sorted.

ULID: the string-native competitor

ULID predates UUIDv7 by several years and solved the same problem before the IETF standardized it. The spec is simpler: 48 bits of timestamp (millisecond precision) followed by 80 bits of randomness. The canonical representation is 26 Crockford base32 characters, all uppercase.

For example: 01JXZM7CZ7KQ1Y2A3B4C5D6E7F.

Because the timestamp is at the front and base32 preserves lexicographic order, sorting the string representation also sorts by time. This is ULID’s biggest practical advantage: it works everywhere that accepts a string, with no binary parsing, no special database type, and no ORM mapping drama. JavaScript handles it natively. Redis sorts it natively. Elasticsearch sorts it natively. Even a bash sort on a text file of ULIDs gives chronological order.

Generating ULIDs in Node.js is a single dependency, ulidx:

import { ulid } from 'ulidx';

const id = ulid(); // => 01JXZM7CZ7KQ1Y2A3B4C5D6E7F

The ulidx library is about 2 kB and has zero dependencies. It also supports a monotonic mode for batch generation inside the same millisecond:

import { monotonicFactory } from 'ulidx';

const ulid = monotonicFactory();
const ids = Array.from({ length: 1000 }, () => ulid());
// ids are strictly sorted

Head-to-head: the details that decide which one you ship

Storage size. This is the biggest difference. UUIDv7 stored as a native uuid in Postgres is 16 bytes. ULID stored as text is 26 bytes, or 32 bytes with the varlena header overhead in some versions. If you use ULID as a foreign key in three related tables, the size penalty multiplies across every index. For a 100 million row table, that is hundreds of megabytes of extra index bloat per relationship. UUIDv7 wins on raw storage.

If you store ULID in a bytea or custom binary type, you can get it down to 16 bytes, but then you lose the string-sorting benefit and most ORMs will hate you. In practice, ULID is treated as text.

Lexicographic sorting guarantees. Both sort by time, but UUIDv7 has a quirk. The canonical string representation includes hyphens (018ff4a0-...), and the version and variant nibbles sit in the middle. Lexicographic string comparison of UUIDv7 works for coarse time bucketing, but if you need a strict ORDER BY on the string form without converting to binary, ULID is safer. In Postgres, if you store UUIDv7 in a native uuid column, binary comparison does the right thing. But if your application serializes to a string, sorts in memory, and compares, the hyphenated format can surprise you.

Time precision. Both use 48-bit millisecond timestamps. That gives you a range until the year 10,889. Good enough. If you need sub-millisecond ordering, neither gives it natively; you need the monotonic counter extensions.

Ecosystem and tooling. UUIDv7 is an IETF standard and inherits every UUID library, validator, and schema format in existence. OpenAPI, JSON Schema, GraphQL, and Protobuf all know what a UUID is. ULID requires custom validators in many frameworks. On the other hand, ULID’s string-native form makes debugging easier. Reading a ULID in a log line immediately tells you the rough time without decoding. Reading a UUIDv7 string tells you very little unless you strip the hyphens and parse hex.

Collision resistance. UUIDv7 has 74 random bits per millisecond. ULID has 80 random bits per millisecond. Both are astronomical. Unless you are generating billions of IDs per second, collisions are a theoretical concern for both.

Monotonicity under load. Node.js’s built-in UUIDv7 and the ulidx monotonic factory both guarantee ordering within a single millisecond. If you use a non-monotonic ULID generator and burst 10,000 inserts in one millisecond, you might get out-of-order suffixes. Check your library.

The Postgres schema that proves the point

Here is a side-by-side table definition. Both use the same payload; only the key type changes.

-- UUIDv7 table: 16-byte native UUID
CREATE TABLE events_v7 (
  id    uuid PRIMARY KEY,
  kind  text NOT NULL,
  data  jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

-- ULID table: 26-char text
CREATE TABLE events_ulid (
  id    text PRIMARY KEY,
  kind  text NOT NULL,
  data  jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

Insert one million rows with each and compare:

SELECT relname,
       pg_size_pretty(pg_relation_size(oid)) AS table_size,
       pg_size_pretty(pg_indexes_size(oid)) AS index_size
FROM pg_class
WHERE relname IN ('events_v7', 'events_ulid');

On a typical test run, the UUIDv7 table’s primary key index is roughly 35-40% smaller than the ULID primary key index. Table size is identical (the payload dominates). But every secondary index on events_ulid that includes the primary key (for example, a covering index on (kind, id)) also pays the 26-byte text tax.

Now check fragmentation after a heavy insert workload:

SELECT relname,
       avg_leaf_density,
       leaf_fragmentation
FROM pgstatindex('events_v7_pkey')
UNION ALL
SELECT relname,
       avg_leaf_density,
       leaf_fragmentation
FROM pgstatindex('events_ulid_pkey');

Both will show low fragmentation (high density, low fragmentation) compared to a UUIDv4 equivalent. That is the point. But the UUIDv7 index will be smaller on disk and in memory.

A safe migration path from UUIDv4

You do not need to rewrite your entire database to benefit from this. For new tables, just switch the generation logic. For existing high-insert tables, a full primary-key migration is usually not worth the downtime.

A pragmatic middle path: add a sortable_id column to the existing table, backfill it with UUIDv7 values derived from the created_at timestamp (plus randomness for uniqueness), and start using that column for new queries that need time-ordered scans. Over time, new related tables reference the sortable_id instead of the old UUIDv4 primary key. The old UUIDv4 column stays for foreign-key stability.

If you are building greenfield, the decision is simpler. Default to UUIDv7 in a native uuid column. It gives you the smallest index footprint, the widest tool support, and a standard you can explain to auditors without naming a GitHub repository.

Reach for ULID when you are in an environment that treats everything as strings, needs URL-safe identifiers without extra encoding, or has debugging workflows where engineers read raw IDs in logs and traces every day. Just budget for the larger index size.

Working Node.js comparison

This snippet generates both, stores them in Postgres, and benchmarks a simple ordered read. It assumes you have a running Postgres and the pg driver installed.

import { randomUUID } from 'node:crypto';
import { ulid } from 'ulidx';
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function insertBatch(table, generator, count) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    for (let i = 0; i < count; i++) {
      await client.query(
        `INSERT INTO ${table} (id, kind, data) VALUES ($1, 'test', '{}')`,
        [generator()]
      );
    }
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

async function orderedRead(table) {
  const t0 = performance.now();
  await pool.query(`SELECT id FROM ${table} ORDER BY id DESC LIMIT 100`);
  return performance.now() - t0;
}

// Generate and measure
await insertBatch('events_v7', () => randomUUID({ version: 7 }), 100_000);
await insertBatch('events_ulid', () => ulid(), 100_000);

console.log('UUIDv7 ordered read:', await orderedRead('events_v7'), 'ms');
console.log('ULID ordered read:', await orderedRead('events_ulid'), 'ms');

await pool.end();

Both ordered reads will be fast because the index is clustered by sort order. The difference shows up at scale in index size and buffer cache pressure, not in a single query microbenchmark.

The decision matrix

SituationPick
Native Postgres uuid type, smallest footprintUUIDv7
Need string-native sorting in Redis, logs, or JS arraysULID
Strict compliance requirements (healthcare, finance)UUIDv7 (IETF standard)
URL-safe IDs without extra encodingULID (base32, no hyphens)
Heavy batch inserts needing monotonic orderingEither, with monotonic mode enabled
ORM that handles uuid natively but treats text PKs suspiciouslyUUIDv7
Debugging culture where engineers read raw IDsULID (timestamp is obvious at a glance)

Neither choice is wrong. Both are dramatically better than UUIDv4 for write-heavy tables. The worst choice is sticking with UUIDv4 because you already have it.

A note from Yojji

Reliable data modeling is the foundation of systems that scale without surprise outages. At Yojji, we design backend architectures where identifier choice, index layout, and query patterns are validated under production load before a single user hits the endpoint. If your team is migrating from legacy UUIDv4 schemas or building new data models that need to grow, our engineering teams can help you get the storage layer right from day one.