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

推荐订阅源

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 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
HMAC Request Signing for Service-to-Service Auth: The Pattern AWS Uses, Simplified
The Practica · 2026-06-10 · via The Practical Developer

Your billing service needs to call the user service to check an account status. The call goes over an internal network, not the public internet, so it is probably fine to skip auth, right? Then someone on the infrastructure slack asks “hey, is anyone’s service making requests to the user admin endpoint?” and nobody fesses up, and you realize that any container on the same Kubernetes cluster can call any other service’s HTTP endpoint without proving who it is.

This is the default state of most internal service meshes. It is also the problem that AWS solved with SigV4, Google Cloud solved with OAuth2 access tokens, and you can solve in about sixty lines of TypeScript with HMAC request signing. No JWT issuer to maintain. No CA to manage. No TLS renegotiation. Just a shared secret, a cryptographic signature over the request, and a timestamp that keeps the whole thing fresh.

The pattern in one picture

Every outgoing HTTP request from Service A to Service B carries an extra header:

Authorization: HMAC-SHA256 credential=service-a,
  signed-headers=host;x-date;content-hash,
  signature=5d4c8a2e...

The receiving service recomputes the signature from the shared secret and the exact same set of request components (method, path, headers, body hash). If the signatures match, the request is authentic. If the timestamp is too old, it is a replay. If the body was tampered in transit, the content hash will not match and the signature fails.

The whole thing takes three pieces: a shared secret store, a signing function on the caller side, and a verification middleware on the receiver side.

Every service pair needs a secret that only those two services know. The simplest approach is a map in an encrypted environment variable:

// secrets.ts
interface ServiceSecrets {
  [serviceName: string]: Buffer;
}

// Loaded from env, e.g. SERVICE_SECRETS='{"user-service":"hex-encoded-256-bit-key","payment-service":"..."}'
function loadSecrets(): ServiceSecrets {
  const raw = process.env.SERVICE_SECRETS;
  if (!raw) throw new Error('SERVICE_SECRETS not set');
  const parsed = JSON.parse(raw);
  const secrets: ServiceSecrets = {};
  for (const [svc, key] of Object.entries(parsed)) {
    secrets[svc] = Buffer.from(key as string, 'hex');
  }
  return secrets;
}

Each key should be a 256-bit (32-byte) cryptographically random value. Generate them with:

openssl rand -hex 32

Store these in your secrets manager (Vault, AWS Secrets Manager, or SOPS-encrypted files). Do not commit them to git. Do not share the same key across three services.

Step 2: The signing function

The caller side takes a request object and produces the Authorization header value. Every component of the request that affects the meaning of the call (method, path, host, body) must be included in the signature.

// sign.ts
import { createHash, createHmac, randomBytes } from 'node:crypto';

interface SignOptions {
  secret: Buffer;
  method: string;
  path: string;
  host: string;
  body?: Buffer | string | object | null;
  date?: Date;
}

interface SignResult {
  authorization: string;
  date: string;
  contentHash: string;
}

export function signRequest(opts: SignOptions): SignResult {
  const date = (opts.date ?? new Date()).toUTCString();
  const bodyBuffer = normalizeBody(opts.body);
  const contentHash = createHash('sha256').update(bodyBuffer).digest('hex');
  const signedHeaders = 'host;x-date;x-content-sha256';

  // Build the string to sign
  const canonicalRequest = [
    opts.method.toUpperCase(),
    opts.path,
    `host:${opts.host}`,
    `x-date:${date}`,
    `x-content-sha256:${contentHash}`,
    '',  // blank line separating headers
    signedHeaders,
    contentHash,
  ].join('\n');

  const signature = createHmac('sha256', opts.secret)
    .update(canonicalRequest)
    .digest('hex');

  const credential = process.env.SERVICE_NAME ?? 'unknown';

  return {
    authorization: [
      `HMAC-SHA256 credential=${credential}`,
      `signed-headers=${signedHeaders}`,
      `signature=${signature}`,
    ].join(', '),
    date,
    contentHash,
  };
}

function normalizeBody(body: unknown): Buffer {
  if (body === null || body === undefined) return Buffer.alloc(0);
  if (Buffer.isBuffer(body)) return body;
  if (typeof body === 'string') return Buffer.from(body);
  return Buffer.from(JSON.stringify(body));
}

The canonical request string is the key design decision. Every byte of it must be reproducible on the receiving side. That means the host must match exactly what the receiver sees, the path must be exactly what was sent (no URL decoding ambiguity), and the body hash must be computed from the raw bytes before any transport encoding.

Step 3: The HTTP client wrapper

Now wrap your HTTP client so every outgoing request gets signed automatically:

// client.ts
import { request, RequestOptions } from 'node:http';

interface ServiceConfig {
  host: string;
  port: number;
  secret: Buffer;
}

export function createSignedClient(config: ServiceConfig) {
  return async function call(
    method: string,
    path: string,
    body?: unknown
  ): Promise<{ status: number; body: string }> {
    const { authorization, date, contentHash } = signRequest({
      secret: config.secret,
      method,
      path,
      host: config.host,
      body,
    });

    return new Promise((resolve, reject) => {
      const opts: RequestOptions = {
        hostname: config.host,
        port: config.port,
        path,
        method,
        headers: {
          'x-date': date,
          'x-content-sha256': contentHash,
          'content-type': body ? 'application/json' : undefined,
          authorization,
        },
      };

      const req = request(opts, (res) => {
        let data = '';
        res.on('data', (chunk) => (data += chunk));
        res.on('end', () => resolve({ status: res.statusCode!, body: data }));
      });

      req.on('error', reject);

      if (body) {
        req.write(JSON.stringify(body));
      }
      req.end();
    });
  };
}

Every single outbound call now carries a verifiable proof of who sent it. No chance for a developer to “forget” to add auth to a new endpoint.

Step 4: The verification middleware

On the receiving side, a middleware extracts the signature and recomputes it:

// middleware.ts (Express-style)
import { Request, Response, NextFunction } from 'express';
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';

interface VerifyOptions {
  secrets: Map<string, Buffer>;
  clockSkewMs?: number;  // default 300000 (5 minutes)
}

export function verifySignature(opts: VerifyOptions) {
  const clockSkew = opts.clockSkewMs ?? 300_000;

  return (req: Request, res: Response, next: NextFunction) => {
    const auth = req.headers.authorization;
    if (!auth || !auth.startsWith('HMAC-SHA256 ')) {
      res.status(401).json({ error: 'missing or malformed authorization' });
      return;
    }

    // Parse the auth header
    const parts = auth.slice('HMAC-SHA256 '.length).split(', ');
    const credential = parts[0]?.split('=')[1];
    const signedHeaders = parts[1]?.split('=')[1];
    const signature = parts[2]?.split('=')[1];

    if (!credential || !signedHeaders || !signature) {
      res.status(401).json({ error: 'malformed authorization header' });
      return;
    }

    // Look up the secret for this caller
    const secret = opts.secrets.get(credential);
    if (!secret) {
      res.status(401).json({ error: 'unknown credential' });
      return;
    }

    // Check timestamp freshness (replay protection)
    const dateStr = req.headers['x-date'] as string | undefined;
    if (!dateStr) {
      res.status(401).json({ error: 'missing x-date header' });
      return;
    }
    const requestTime = new Date(dateStr).getTime();
    const now = Date.now();
    if (Number.isNaN(requestTime) || Math.abs(now - requestTime) > clockSkew) {
      res.status(401).json({ error: 'request expired or clock skew too large' });
      return;
    }

    // Compute content hash from the raw body
    const rawBody = (req as any).rawBody as Buffer | undefined;
    const contentHash = createHash('sha256')
      .update(rawBody ?? Buffer.alloc(0))
      .digest('hex');

    const providedHash = req.headers['x-content-sha256'] as string;
    if (contentHash !== providedHash) {
      res.status(401).json({ error: 'body hash mismatch (tampered in transit?)' });
      return;
    }

    // Rebuild the canonical request
    const host = req.headers.host ?? 'localhost';
    const canonicalRequest = [
      req.method,
      req.originalUrl || req.url,
      `host:${host}`,
      `x-date:${dateStr}`,
      `x-content-sha256:${contentHash}`,
      '',
      signedHeaders,
      contentHash,
    ].join('\n');

    const expectedSignature = createHmac('sha256', secret)
      .update(canonicalRequest)
      .digest('hex');

    // Constant-time comparison to prevent timing attacks
    const sigBuf = Buffer.from(signature, 'hex');
    const expectedBuf = Buffer.from(expectedSignature, 'hex');
    if (
      sigBuf.length !== expectedBuf.length ||
      !timingSafeEqual(sigBuf, expectedBuf)
    ) {
      res.status(401).json({ error: 'signature mismatch' });
      return;
    }

    // Attach verified caller identity to the request
    (req as any).verifiedCaller = credential;
    next();
  };
}

This middleware needs access to the raw request body before Express parses it, because JSON parsing can change whitespace. Wire it up like this:

// app.ts
import express from 'express';
import { verifySignature } from './middleware';

const app = express();

// Capture raw body for signature verification (BEFORE JSON parser)
app.use(express.raw({ type: '*/*', verify: (req, _res, buf) => {
  (req as any).rawBody = buf;
} }));

app.use(verifySignature({
  secrets: loadSecretsMap(),
}));

// Now safe to parse JSON
app.use(express.json());

app.get('/api/account', (req, res) => {
  // req.verifiedCaller is the authenticated service name
  res.json({ service: req.verifiedCaller });
});

Why HMAC-SHA256 and not JWT or mTLS

HMAC request signing sits in a specific slot on the auth spectrum.

JWT requires a central issuer. Every service that wants to verify a token needs to fetch the signing key from the issuer, cache it, and handle rotation. If the issuer goes down, new services cannot start. This works well for user-facing sessions (the login flow bootstraps the token). It is overkill for a fixed set of internal services that should trust each other.

mTLS is cryptographically excellent and is the right choice if you already have a service mesh (Istio, Linkerd) managing the certificates for you. Without a mesh, you are managing per-service certificates, a CA, renewal cron jobs, and the operational complexity of rotating a CA when a key leaks. For a team that does not run a dedicated platform team, mTLS is a lot of ceremony.

API keys (a static string in a header) are the simplest option and also the least secure. They cannot prove that the request body was not tampered with. They are valid forever unless rotated. They leak in logs, in error messages, and in the occasional debug dump that gets pasted into GitHub issues. HMAC signing addresses all three weaknesses without adding a central dependency.

HMAC request signing is the pragmatic middle: no infrastructure dependencies, no certificate lifecycle, just a shared secret and a cryptographic proof that travels with every request.

When to step up to Ed25519

HMAC works great inside a single trust domain (your VPC, your Kubernetes cluster). The moment you need to authenticate requests that cross organizational boundaries, or you need non-repudiation (proof that Service A sent a specific request, verifiable by a third party), switch to asymmetric signing with Ed25519.

// ed25519-sign.ts
import { createSign, createVerify } from 'node:crypto';

export function signEd25519(privateKey: Buffer, canonicalRequest: string): string {
  const sign = createSign('ed25519');
  sign.update(canonicalRequest);
  return sign.sign(privateKey).toString('hex');
}

export function verifyEd25519(
  publicKey: Buffer,
  canonicalRequest: string,
  signature: string
): boolean {
  const verify = createVerify('ed25519');
  verify.update(canonicalRequest);
  return verify.verify(publicKey, signature, 'hex');
}

Ed25519 signatures are small (64 bytes), fast to compute, and the public key can be distributed freely without compromising the signing key. Use this when Service A should be able to prove to an auditor that “Service B really did send request X” without revealing Service B’s private key.

For everything else, HMAC-SHA256 with a 256-bit key is the right call.

Key rotation without downtime

Secrets should not live forever. Rotate them on a schedule (every 90 days is a common baseline). The trick is to support multiple valid keys during the rotation window:

function loadSecretsMap(): Map<string, Buffer> {
  const primary = loadSecrets();
  const map = new Map<string, Buffer>();

  // Primary keys
  for (const [svc, key] of Object.entries(primary)) {
    map.set(svc, key);
  }

  // Rotating keys from a separate env var (e.g. ROTATING_SERVICE_SECRETS)
  const rotatingRaw = process.env.ROTATING_SERVICE_SECRETS;
  if (rotatingRaw) {
    const rotating = JSON.parse(rotatingRaw);
    for (const [svc, key] of Object.entries(rotating)) {
      if (!map.has(svc)) {
        map.set(svc, Buffer.from(key as string, 'hex'));
      }
    }
  }

  return map;
}

When rotating, deploy the new key into ROTATING_SERVICE_SECRETS on the receiver side first (making it accept both old and new signatures), then update the caller side to use the new key, then remove the old key from SERVICE_SECRETS. This gives you a clean cutover with no window where signatures fail.

The tests that prove it works

A signing scheme is worthless if it breaks on the first edge case. Cover these scenarios:

// sign.test.ts
import { signRequest } from './sign';
import { createHmac } from 'node:crypto';

describe('signRequest', () => {
  const secret = Buffer.from('00'.repeat(32), 'hex');
  const baseOpts = {
    secret,
    method: 'POST',
    path: '/api/account/123',
    host: 'user-service.internal',
    body: { userId: 123 },
  };

  it('produces a consistent signature for the same inputs', () => {
    const a = signRequest(baseOpts);
    const b = signRequest(baseOpts);
    expect(a.signature).toBe(b.signature);
  });

  it('produces a different signature when the body changes', () => {
    const a = signRequest(baseOpts);
    const b = signRequest({ ...baseOpts, body: { userId: 456 } });
    expect(a.signature).not.toBe(b.signature);
  });

  it('produces a different signature when the path changes', () => {
    const a = signRequest(baseOpts);
    const b = signRequest({ ...baseOpts, path: '/api/account/456' });
    expect(a.signature).not.toBe(b.signature);
  });

  it('produces a different signature for a different HTTP method', () => {
    const a = signRequest(baseOpts);
    const b = signRequest({ ...baseOpts, method: 'DELETE' });
    expect(a.signature).not.toBe(b.signature);
  });

  it('rejects requests with expired timestamps', () => {
    const oldDate = new Date(Date.now() - 600_000); // 10 minutes ago
    const result = signRequest({ ...baseOpts, date: oldDate });
    // The receiver middleware with 5-min skew should reject this
    const skew = 300_000;
    const age = Date.now() - oldDate.getTime();
    expect(age).toBeGreaterThan(skew);
  });
});

The receiver tests should verify that tampered headers, replayed requests, and unknown credentials all return 401 before the request body is ever parsed.

Where this breaks down and what to watch for

This pattern has limits. Know them before you bet your production traffic on it.

No delegation. If Service A calls Service B on behalf of a user, Service B knows that Service A sent the request, but not which user. You need a separate user identity token (a JWT or session cookie) for that. The HMAC signature proves the caller’s machine identity, not the user’s.

Clock skew. Every service needs reasonably synchronized clocks (within 5 minutes is safe; within 60 seconds is better). A service whose clock drifts by 10 minutes will fail every request. Use NTP on every node.

Secret leaks. A compromised secret lets an attacker impersonate a service until the secret is rotated. Audit who has access to the secrets store. Rotate immediately after any suspected compromise.

Log leakage. The authorization header value is not secret (it is a signature, not a key), but the x-content-sha256 header reveals that two requests had identical bodies. If your threat model considers this a side channel, include a unique nonce in the canonical request string.

The practical takeaway

Sixty lines of signing logic. One middleware. One environment variable per service pair. No JWT issuer to maintain, no CA to stand up, no mTLS certificate rotation to babysit.

HMAC request signing is the pragmatic default for internal service-to-service auth. It solves three problems at once: it proves who sent the request, it proves the request was not tampered with, and the timestamp window prevents replay attacks. It is not the most sophisticated auth scheme in the world, but it is the one that most teams should reach for before they build a JWT infrastructure they do not need.

Add it in an afternoon. Test it in the morning. Ship it by lunch.


A note from Yojji

This post covers the kind of infrastructure decision that never makes a product demo but decides whether your platform survives its first real security review. Getting the details right (constant-time comparison, canonical request formatting, safe key rotation) is the difference between auth that works and auth that gives a false sense of safety.

That kind of production-grade systems engineering is exactly what Yojji ships. Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their teams specialize in the JavaScript stack (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and microservices architecture. They run dedicated senior outstaffed teams alongside full-cycle product engagements covering discovery, design, development, QA, and DevOps.

If your team would rather adopt proven internal-auth patterns than debug the consequences of skipping auth between services, Yojji is worth a conversation.