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

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

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 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 Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies 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
MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40%
The Practica · 2026-05-21 · via The Practical Developer

The internal inventory service was handling 12,000 requests per second during the flash sale and the p95 latency had crept from 8 ms to 34 ms. The CPU profile showed 22% of total cycles inside JSON.stringify and JSON.parse. The payloads were not even large by web standards, 4-8 KB of nested catalog data, but every service in the call graph was serializing and deserializing the same objects. The load test made it obvious: we were not network-bound. We were syntax-bound.

The fix was not “buy bigger instances.” The fix was replacing JSON with MessagePack for internal service-to-service communication. MessagePack is a binary serialization format that maps directly to JSON’s type system (null, boolean, number, string, array, object) but encodes it in a compact binary form. For our workload, it cut average payload size by 35% and parse CPU by nearly half. The public REST API still returns JSON for browser clients. The internal RPC layer switched to binary without touching a single route handler.

This post walks through the benchmark that justified the switch, the Node.js implementation with msgpackr, and the content-negotiation middleware that lets you migrate service by service without a big bang.

Why JSON.stringify is a bad default for internal RPC

JSON is human-readable, universally supported, and the obvious choice for any API. Those are the exact reasons it is wasteful inside a datacenter where no human reads the wire format.

Every number in JSON is a text string. The integer 42 takes two bytes. The integer 100000 takes six bytes. In MessagePack, both fit in a single type-prefix byte plus up to four bytes of binary representation. A boolean is 4-5 bytes in JSON (true or false) and one byte in MessagePack. A long string is surrounded by quote characters that do not carry data. Every object key is repeated in full on every message, even if the schema is identical across millions of requests.

The CPU cost is worse than the size cost. JSON.stringify must iterate the object graph, convert every number to decimal text, escape every string, and allocate a large intermediate string. JSON.parse must run a full lexer and parser on that text. V8 optimizes both, but they are still fundamentally text-processing operations on a hot path. On a 4 KB payload at 10k RPS, that is 40 MB of text generated and parsed every second.

MessagePack replaces all of that with a binary encoder that writes type tags and raw bytes directly. No decimal conversion. No escaping. No quote characters. The resulting buffer is smaller, and the encode/decode path is faster because the format is designed for machines, not humans.

What MessagePack actually is (and is not)

MessagePack is not a compressed text format like gzip. It is a typed binary interchange format, similar to Protocol Buffers but schemaless. You do not define a .proto file. You encode a plain JavaScript object and get back a Buffer. The receiver decodes it back to the same shape. Arrays stay arrays. Objects stay objects. null, undefined, strings, numbers, booleans, and even Date and Buffer values have defined representations.

The format uses a leading type byte to describe what follows. For example:

  • 0x01 means the next value is a positive fixint (values 0 to 127 encoded in the byte itself).
  • 0xcc means the next byte is an unsigned 8-bit integer.
  • 0xcd means the next two bytes are an unsigned 16-bit integer, big-endian.
  • 0xa3 means the next three bytes form a UTF-8 string.

Because the type is explicit, the decoder does not scan for closing braces or quotes. It reads the type, reads the known number of payload bytes, and moves on. This is why MessagePack parse is roughly 2-5x faster than JSON.parse on typical service payloads, and the output is 20-40% smaller.

MessagePack is also not a substitute for schema evolution tooling. Unlike Protobuf or Avro, it does not have a schema registry. If you add a field to the sender and the receiver is running old code, the decoder simply ignores the unknown field. If you rename a field, the old name disappears and the new one is ignored by old consumers. For internal RPC between services you control, this is usually acceptable, but it means you still need discipline around breaking changes.

The Node.js implementation: msgpackr

There are two solid MessagePack libraries for Node.js. @msgpack/msgpack is the reference implementation, pure JavaScript, and works in browsers. msgpackr is a native C++ addon that is dramatically faster and the right choice for backend services. We use msgpackr for internal RPC.

npm install msgpackr

Basic encode and decode:

import { pack, unpack } from 'msgpackr';

const payload = {
  sku: 'SKU-91823',
  quantity: 42,
  price: 1999.99,
  inStock: true,
  tags: ['electronics', 'sale'],
  metadata: { warehouse: 'US-West' },
};

const buffer = pack(payload);
console.log('MessagePack size:', buffer.length);

const decoded = unpack(buffer);
console.log(decoded.price); // 1999.99

For streaming or network boundaries, msgpackr provides a Unpackr class that can parse partial buffers incrementally, which is useful when reading from a TCP socket or an HTTP response stream:

import { Unpackr } from 'msgpackr';

const unpackr = new Unpackr();

// In your HTTP response handler:
response.on('data', (chunk) => {
  const messages = unpackr.unpackMultiple(chunk);
  for (const msg of messages) {
    processMessage(msg);
  }
});

msgpackr also supports a structuredClone extension out of the box, so Date, Buffer, Map, and Set instances survive the round-trip. That alone eliminates a class of “date came back as a string” bugs that JSON forces you to handle manually.

The benchmark: real numbers on a service payload

Here is a benchmark on a representative internal payload, roughly 5 KB as JSON. It contains nested arrays, integer IDs, float prices, booleans, and short string keys.

import { pack, unpack } from 'msgpackr';
import { randomUUID } from 'node:crypto';

function generatePayload() {
  return {
    orderId: randomUUID(),
    items: Array.from({ length: 20 }, (_, i) => ({
      sku: `SKU-${i.toString().padStart(5, '0')}`,
      qty: Math.floor(Math.random() * 10) + 1,
      unitPrice: parseFloat((Math.random() * 500).toFixed(2)),
      available: Math.random() > 0.1,
    })),
    warehouse: 'US-West-1',
    priority: 2,
    metadata: { batchId: randomUUID(), source: 'web' },
  };
}

const payload = generatePayload();
const jsonBuf = Buffer.from(JSON.stringify(payload));
const msgBuf = pack(payload);

console.log('JSON size:', jsonBuf.length);
console.log('MessagePack size:', msgBuf.length);

// Encode benchmark
const iterations = 100_000;
const t0 = performance.now();
for (let i = 0; i < iterations; i++) pack(payload);
const encodeMsg = performance.now() - t0;

const t1 = performance.now();
for (let i = 0; i < iterations; i++) JSON.stringify(payload);
const encodeJson = performance.now() - t1;

console.log(`MessagePack encode: ${encodeMsg.toFixed(2)}ms`);
console.log(`JSON encode: ${encodeJson.toFixed(2)}ms`);

// Decode benchmark
const t2 = performance.now();
for (let i = 0; i < iterations; i++) unpack(msgBuf);
const decodeMsg = performance.now() - t2;

const t3 = performance.now();
for (let i = 0; i < iterations; i++) JSON.parse(jsonBuf);
const decodeJson = performance.now() - t3;

console.log(`MessagePack decode: ${decodeMsg.toFixed(2)}ms`);
console.log(`JSON decode: ${decodeJson.toFixed(2)}ms`);

On a typical Linux x86_64 box running Node.js 22, the output looks like this:

JSON size: 5124
MessagePack size: 3291
MessagePack encode: 124ms
JSON encode: 312ms
MessagePack decode: 98ms
JSON decode: 278ms

That is 36% smaller, 2.5x faster on encode, and 2.8x faster on decode. At 10,000 requests per second, the difference between 312 ms and 124 ms of CPU time per thousand iterations is the difference between running three instances and running eight.

Middleware: transparent content negotiation

The migration rule we used was simple. Public API endpoints stay JSON forever. Internal service clients send an Accept: application/msgpack header, and the server returns MessagePack when requested. If the header is absent or says application/json, the server falls back to JSON. This lets you migrate one consumer at a time without a deploy-time flag day.

Here is an Express middleware that serializes the response body based on the Accept header. It assumes you have already built the response object in memory.

import { pack } from 'msgpackr';
import type { Request, Response, NextFunction } from 'express';

function serializerMiddleware(req: Request, res: Response, next: NextFunction) {
  const originalJson = res.json.bind(res);

  res.sendPayload = (payload: unknown) => {
    const accepted = req.get('Accept') || 'application/json';
    if (accepted.includes('application/msgpack')) {
      res.set('Content-Type', 'application/msgpack');
      res.send(pack(payload));
    } else {
      originalJson(payload);
    }
  };

  next();
}

// Usage in a route:
app.get('/inventory/:sku', serializerMiddleware, async (req, res) => {
  const data = await fetchInventory(req.params.sku);
  res.sendPayload(data);
});

On the client side, a small wrapper around fetch checks whether the server returned MessagePack and decodes it automatically:

import { unpack } from 'msgpackr';

async function serviceFetch(url: string, options: RequestInit = {}) {
  const res = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Accept: 'application/msgpack, application/json;q=0.9',
    },
  });

  const ct = res.headers.get('Content-Type') || '';
  if (ct.includes('application/msgpack')) {
    const buffer = Buffer.from(await res.arrayBuffer());
    return unpack(buffer);
  }
  return res.json();
}

This pattern works for any HTTP client that can read raw bytes. In our stack, we applied it to the internal service mesh layer (a simple proxy) so individual developers did not have to think about serialization at all. The mesh detects the Accept header and transparently serializes the JSON response to MessagePack before sending it over the wire.

The gotchas you will hit

Schema evolution is silent. MessagePack ignores unknown fields by default. If you rename warehouse to fulfillmentCenter, old consumers will receive an object with no warehouse field and no fulfillmentCenter field. No error, just missing data. For internal APIs, the fix is the same as with JSON: treat additive changes as safe, and never rename or retype existing fields without versioning the endpoint.

Binary payloads are opaque. When a request fails, you cannot curl the endpoint and read the response. You need a small CLI decoder, or you configure your internal gateway to transcode MessagePack back to JSON for error logging. We added a debug mode where ?debug=1 forces JSON regardless of the Accept header, which makes incident response easier.

Browser support does not matter for internal RPC. If you accidentally expose a MessagePack endpoint to a browser, the client will download binary and have no idea what to do with it. The content-negotiation fallback prevents this, but you should audit your API gateway rules to make sure public routes do not advertise application/msgpack.

Compression interaction. If you already gzip your JSON payloads, the size win from MessagePack is smaller, because gzip compresses repeated object keys very well. In our tests, gzipped MessagePack was still 10-15% smaller than gzipped JSON, and the parse CPU win remained unchanged. The biggest gains come from uncompressed internal traffic inside a VPC, where you may not be gzipping at all to save CPU.

When to keep JSON

Do not switch everything. Keep JSON for:

  • Public REST or GraphQL APIs consumed by browsers.
  • Configuration files, logs, and anything a human reads.
  • Endpoints with wildly dynamic schemas where object keys are not predictable. MessagePack handles this, but the size win shrinks when keys are long and non-repeating.
  • Debugging endpoints and health checks where curl readability is worth more than a millisecond of latency.

Switch to MessagePack for:

  • Internal gRPC-like HTTP services with stable schemas.
  • High-frequency RPC between Node.js, Go, or Python services (all have solid MessagePack libraries).
  • Message queue payloads where you control both producer and consumer.
  • Any path where the flame graph shows JSON.parse or JSON.stringify eating more than 5% of CPU.

A note from Yojji

Efficient serialization is one of those details that separates systems that scale linearly from systems that hit a wall at 10k RPS. At Yojji, we profile internal service boundaries early in the architecture phase, and we have replaced JSON with MessagePack on multiple high-throughput Node.js platforms without breaking existing contracts. If your microservices are spending too much time in text parsing, our backend engineering teams can help you build a migration path that keeps every consumer compatible.