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

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
腾讯CDC
V
V2EX
Martin Fowler
Martin Fowler
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
博客园 - 【当耐特】
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
K
Kaspersky official blog
Security Latest
Security Latest
H
Help Net Security
博客园_首页
美团技术团队
Spread Privacy
Spread Privacy
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
G
Google Developers Blog
NISL@THU
NISL@THU
爱范儿
爱范儿
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic
P
Privacy International News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
I
InfoQ
The Cloudflare Blog
F
Full Disclosure
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
From Resilience4j to TypeScript: Build the JVM Patterns You Already Know
Gabriel Anha · 2026-05-03 · via DEV Community

You joined a Node service. The first ticket says: make paymentService.charge resilient: circuit breaker, retry on 5xx, rate limit per merchant. On the JVM the answer is muscle memory:

@CircuitBreaker(name = "payments", fallbackMethod = "fallback")
@Retry(name = "payments")
@RateLimiter(name = "payments")
public Receipt charge(Charge req) {
    return gateway.send(req);
}

Enter fullscreen mode Exit fullscreen mode

Five lines. Three resilience guarantees. The @CircuitBreaker and @Retry annotations come from Resilience4j, the @RateLimiter either there or in Spring Cloud, and the AOP machinery wraps charge at startup. The method body has zero idea any of this is happening.

You open VS Code, type @Circuit, and wait for autocomplete. Nothing. You search npm for "resilience4j typescript". A handful of half-maintained ports show up. None match. You look at the Spring docs link from the ticket and feel the floor tilt: the framework I rely on for this isn't here at all.

The patterns are still here. Circuit breaker, retry, bulkhead, rate limiter, time limiter, fallback, cache: every one of them ports to TypeScript and runs in production at companies you've heard of. What changed is the shape. JVM resilience is annotations on methods. TypeScript resilience is functions that wrap functions.

Once you internalise that shift, the rest is mechanical: pick a wrapper library, compose the policies you need, pass the wrapped function around.

What Resilience4j actually ships

Resilience4j is the Hystrix successor most JVM teams settled on after Netflix moved Hystrix into maintenance mode in 2018. The Resilience4j docs ship six core modules: CircuitBreaker (open / half-open / closed state machine), Retry (N attempts with backoff and jitter), RateLimiter (token bucket or fixed window), Bulkhead (concurrency cap, in SemaphoreBulkhead and ThreadPoolBulkhead flavours), TimeLimiter (deadline-driven TimeoutException), and Cache (JCache-backed memoisation). The @CircuitBreaker / @Retry / @Bulkhead / @RateLimiter / @TimeLimiter annotations wire those decorators in through Spring's AOP proxies, configuration lives in application.yml, and metrics ship to Micrometer. The whole thing is a four-line dependency add and a config block.

That density is what JVM developers miss when they land in TypeScript. The patterns are not exotic. They're commodity infrastructure on the JVM.

TypeScript has the patterns, not the annotations

TC39's decorators proposal reached Stage 3 in March 2022 and TypeScript 5.0 shipped native support in March 2023. Decorators exist in the language. Frameworks that use them (NestJS, TypeORM, class-validator) feel familiar to a Spring developer.

Most TypeScript code does not use them. Most TypeScript code is plain functions and modules. There's no Spring container scanning your beans at startup, no AOP proxy generated around your class, no annotation processor reading metadata at runtime. NestJS adds that machinery on top, and inside a NestJS service you can write @UseInterceptors(CircuitBreakerInterceptor) and have something close to the JVM experience. Outside NestJS (plain Express, Fastify, Hono, Bun.serve, a worker script), decorators are an unusual choice.

The reason is structural. JavaScript decorators are call-time wrappers around functions and class members. They don't have a DI container behind them, so you'd have to build one to make the annotation style pay off. The shorter path is the one the ecosystem actually took: ship the wrapper directly.

Sketch of the shape (the real Cockatiel API is in the next section):

const charge = withCircuitBreaker(
  withRetry(
    withRateLimiter(rawCharge, { tokensPerInterval: 100, interval: 1000 }),
    { maxAttempts: 3, backoff: "exponential" },
  ),
  { failureThreshold: 0.5, openFor: 30_000 },
);

await charge(req);

Enter fullscreen mode Exit fullscreen mode

Three function calls, each returning a function that wraps the next one. No annotations. No reflection. The composition is visible at the call site, and the wrapped charge is another value you pass around. That is the shift.

Side-by-side: Spring vs TypeScript, same service

Take a payment service that needs all of: circuit breaker, retry, rate limiter. The JVM version uses three Resilience4j annotations:

@Service
public class PaymentService {

    @CircuitBreaker(name = "gateway", fallbackMethod = "denied")
    @Retry(name = "gateway")
    @RateLimiter(name = "gateway")
    public Receipt charge(Charge req) {
        return gateway.send(req);
    }

    public Receipt denied(Charge req, Throwable t) {
        return Receipt.failed(t.getMessage());
    }
}

Enter fullscreen mode Exit fullscreen mode

Configuration in application.yml:

resilience4j:
  circuitbreaker:
    instances:
      gateway:
        failureRateThreshold: 50
        waitDurationInOpenState: 30s
  retry:
    instances:
      gateway:
        maxAttempts: 3
        waitDuration: 250ms
  ratelimiter:
    instances:
      gateway:
        limitForPeriod: 100
        limitRefreshPeriod: 1s

Enter fullscreen mode Exit fullscreen mode

The TypeScript version is the same shape, in code:

import {
  circuitBreaker,
  retry,
  ConsecutiveBreaker,
  ExponentialBackoff,
  handleAll,
  wrap,
} from "cockatiel";
import { RateLimiterMemory } from "rate-limiter-flexible";

const limiter = new RateLimiterMemory({
  points: 100,
  duration: 1, // per second
});

const policy = wrap(
  circuitBreaker(handleAll, {
    halfOpenAfter: 30_000,
    breaker: new ConsecutiveBreaker(5),
  }),
  retry(handleAll, {
    maxAttempts: 3,
    backoff: new ExponentialBackoff({ initialDelay: 250 }),
  }),
);

// gateway.send: (req: Charge) => Promise<Receipt>
export async function charge(req: Charge): Promise<Receipt> {
  await limiter.consume(req.merchantId);
  try {
    return await policy.execute(() => gateway.send(req));
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    return Receipt.failed(message);
  }
}

Enter fullscreen mode Exit fullscreen mode

Two functions doing the same job, expressed in two different shapes. In the Spring version the annotations declare what charge is. In the TypeScript version the code constructs it. Both ship to production. Both behave identically against a stubbed gateway.send.

A JVM developer's first instinct on reading the TS code is "this is more verbose". It is, by line count. What you get back is everything is a value: policy is a regular object, charge is a regular function, both go into a Map, both serialise into snapshot tests, both behave under vi.useFakeTimers() without any AOP-aware testing harness. The annotation magic in Spring buys density. The cost: at runtime you can't tell what's actually wrapping the method without reading the proxy chain in a debugger. TypeScript's tradeoff goes the other way.

Cockatiel, the closest thing to Resilience4j

When a JVM developer asks "what's the TS equivalent of Resilience4j", the honest answer is Cockatiel. It was started by Connor Peet, a Microsoft engineer on the VS Code team, and ships the same six policy types Resilience4j ships, with the same composability story.

What Cockatiel covers:

  • retry(...)maxAttempts, ConstantBackoff, ExponentialBackoff, IterableBackoff for custom delay schedules. Filter on errors via handleType, handleWhen, handleResultType.
  • circuitBreaker(...)ConsecutiveBreaker, SamplingBreaker (rolling window failure rate), CountBreaker. halfOpenAfter and state events.
  • bulkhead(concurrency, queue) — cap concurrent and queued executions.
  • timeout(ms, strategy)Cooperative (passes a signal) or Aggressive (rejects regardless).
  • fallback(handle, value) — return a default on failure.
  • wrap(...policies) — compose, outer-to-inner. wrap(circuit, retry) runs retry inside circuit; the breaker only sees the final result of the retry block.

A real composed policy:

import {
  bulkhead,
  circuitBreaker,
  ConsecutiveBreaker,
  ExponentialBackoff,
  handleAll,
  retry,
  timeout,
  TimeoutStrategy,
  wrap,
} from "cockatiel";

const policy = wrap(
  bulkhead(10, 50),
  circuitBreaker(handleAll, {
    halfOpenAfter: 30_000,
    breaker: new ConsecutiveBreaker(5),
  }),
  retry(handleAll, {
    maxAttempts: 3,
    backoff: new ExponentialBackoff(),
  }),
  timeout(2_000, TimeoutStrategy.Cooperative),
);

const result = await policy.execute(({ signal }) =>
  fetch(url, { signal }).then((r) => r.json()),
);

Enter fullscreen mode Exit fullscreen mode

Read inside-out: the leaf fetch is given a 2-second cooperative timeout (Cockatiel passes you an AbortSignal you should plumb into fetch). If it fails, retry kicks in for up to 3 attempts with exponential backoff. The retry block sits behind a circuit breaker that opens after 5 consecutive failures. The whole thing is gated by a bulkhead that allows 10 concurrent in-flight calls plus 50 queued.

This is the same composition Resilience4j gives you with Decorators.ofSupplier(...).withRetry(...).withCircuitBreaker(...).withBulkhead(...).withTimeLimiter(...). Function-level, not annotation-level, but the policies and the order of application are the same.

For rate limiting, Cockatiel doesn't ship a primitive; the de-facto choice is rate-limiter-flexible, which gives you token-bucket and leaky-bucket implementations backed by memory, Redis, MongoDB, or Postgres. For caching the call result, p-memoize plus quick-lru is the small, focused combo most teams pick. None of these talk to each other automatically, but each is a function that wraps a function, which is the whole point.

The decorator-vs-wrapper mental shift

Walk through what changes when you stop looking for @CircuitBreaker.

Composition is explicit. In Spring, @CircuitBreaker and @Retry on the same method get applied in an order determined by aspect ordering: Ordered constants, @Order annotations, or framework defaults. The order matters (retry inside the breaker vs breaker inside the retry are very different behaviours), and the order is invisible at the call site. In TypeScript, wrap(circuit, retry) and wrap(retry, circuit) are different expressions. You can read which is outer and which is inner.

Wrapped functions are values. The wrapped charge is just a function. You can hold it in a variable, pass it to a queue worker, snapshot-test it, hand it to a test double, swap it out per-environment. The Spring proxy is also a value, but you have to ask the application context for it, and the bean's identity at runtime is not the class you wrote — it's a generated CGLIB or JDK proxy subclass. Tests for @CircuitBreaker end up being integration tests with Spring loaded.

No DI container is required. Resilience4j's annotation magic depends on Spring AOP, which depends on the ApplicationContext. Strip Spring out and the annotations stop doing anything — they're just metadata on a method nobody reads. Cockatiel runs the same in a Node script, an AWS Lambda, a Cloudflare Worker, a Bun HTTP server, a Deno cron, a Vite-bundled browser app. There's no container to bring up.

Configuration lives in code. Spring's application.yml profile system lets ops change a circuit breaker's threshold without a redeploy. The TypeScript equivalent is reading the threshold from process.env and rebuilding the policy on startup, or using a config service and rebuilding the policy on change. Both work; the JVM version is more declarative and the TS version is more direct. Pick the one that matches your deploy story.

The shift, said one way: JVM resilience is declared on a method. TypeScript resilience is built into a function. Once that lands, every Resilience4j primitive has a clean port.

Quick translation table

Resilience4j TypeScript equivalent
@CircuitBreaker(name = "x") circuitBreaker(handleAll, { breaker: new ConsecutiveBreaker(n), halfOpenAfter: ms }) from Cockatiel
@Retry(name = "x") retry(handleAll, { maxAttempts: n, backoff: new ExponentialBackoff() }) from Cockatiel
@RateLimiter(name = "x") RateLimiterMemory / RateLimiterRedis from rate-limiter-flexible, await limiter.consume(key)
@Bulkhead(name = "x") (semaphore) bulkhead(concurrency, queue) from Cockatiel
@Bulkhead(type = THREADPOOL) a worker pool (Piscina, BullMQ workers) — the model is different
@TimeLimiter(name = "x") timeout(ms, TimeoutStrategy.Cooperative) from Cockatiel, or AbortSignal.timeout(ms)
@Cache(cacheName = "x") p-memoize over a quick-lru or Redis-backed cache
Decorators.ofSupplier(...).withRetry(...).withCircuitBreaker(...) wrap(circuitBreaker(...), retry(...)) from Cockatiel
Resilience4j Micrometer metrics Cockatiel policy.onSuccess / onFailure / onBreak events into your metrics client
application.yml config block env-driven config, parsed at startup, passed to the wrapper constructors
Spring @Order on aspects argument order in wrap(...)

The one row where the shape doesn't match is @Bulkhead(type = THREADPOOL). That assumes a JVM thread pool you can offload work to. Node, Bun, and Deno are single-threaded for user code; CPU-bound parallelism comes from Worker threads with explicit message passing. The SemaphoreBulkhead row maps cleanly because it's I/O concurrency, which translates directly. The thread-pool row is genuinely lossy and the right answer is usually a job queue (BullMQ, Quirrel, Inngest) rather than an in-process pool.

Wrappers are the substrate

NestJS interceptors give you the annotation feel on top of the same wrapper machine. Decorators in TS are sugar over wrappers, the same way async is sugar over Promise. Reach for the wrappers first and the decorators-when-you-want-them story is additive instead of foundational.

Once you stop searching for @CircuitBreaker and start writing wrap(circuitBreaker(...), retry(...)), the move is mostly done.

If this was useful

The TypeScript Library is a 5-book collection that maps cleanly to where you start:

  • TypeScript EssentialsAmazon — entry point. Types, narrowing, modules, async, daily-driver tooling.
  • The TypeScript Type SystemAmazon — deep dive. Generics, mapped/conditional types, infer, template literals, branded types.
  • Kotlin and Java to TypeScriptAmazon — bridge for JVM developers. Variance, null safety, sealed→unions, coroutines→async/await.
  • PHP to TypeScriptAmazon — bridge for PHP 8+ developers. Sync→async paradigm, generics, discriminated unions.
  • TypeScript in ProductionAmazon — production layer. tsconfig, build tools, monorepos, library authoring, dual ESM/CJS, JSR.

Books 1 and 2 are the core path. Books 3 and 4 substitute for 1 and 2 if you're coming from JVM or PHP — this post is a sample of what book 3 covers. Book 5 is for anyone shipping TypeScript at work.

All five books ship in ebook, paperback, and hardcover.

The TypeScript Library — the 5-book collection