Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. REST APIs

Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency

Toxiproxy adds 3,000 ms to billing, and a ticket list that never calls billing gets a p95 of 8,931 ms because all 10 threads are waiting. A 500 ms timeout, a bulkhead of three, a breaker over ten calls and one retry bring it to 6 ms, with 2,292 plan calls answered by the fallback. Remove the delay and the breaker closes by itself.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026REST APIs

What you will learn

  • Show how one slow dependency fills every request thread, using Toxiproxy and k6
  • Set a read timeout on RestClient so a thread is never held forever
  • Configure a Resilience4j circuit breaker, bulkhead and retry in plain Java and wrap one call in the right order
  • Return a planned fallback and watch the breaker close again on its own

Before you start

  • Spring Boot REST controllers and RestClient
  • Docker Compose basics

A slow dependency can take down features that never call it. This article shows that happening on a small Spring Boot desk called FuseBox, then fixes it with a timeout, a circuit breaker, a bulkhead, one retry and a fallback from Resilience4j. Toxiproxy sits in front of the billing service so the slowness repeats on cue. The same patterns for model calls, with retry budgets, are in retry budgets and circuit breakers for LLM calls.

One slow call takes every thread

The desk has 10 request threads (server.tomcat.threads.max: 10) and two features that matter here. /api/tickets calls nothing. /api/plan calls billing. (A third endpoint, /api/breaker, reports the breaker state.)

@GetMapping("/tickets")
Map<String, Object> tickets() {
    return Map.of("open", 3);                 // no dependency at all
}

@GetMapping("/plan")
Map<String, Object> plan() {
    return billing.plan();                    // depends on billing
}

Billing is healthy, and the desk reaches it through Toxiproxy. One call to the proxy adds a latency toxic of 3,000 ms:

$ curl -s localhost:18320/api/plan
{"plan":"pro"}
$ curl -s -X POST localhost:18474/proxies/billing/toxics -o /dev/null -w "%{http_code}" -d '{"name":"slow","type":"latency","attributes":{"latency":3000}}'
200

With protection off, the client waits as long as billing takes:

Map<String, Object> plan() {
    if (!settings.protect()) {
        return fetch();                        // waits as long as billing takes
    }
    ...
}

k6 then sends 30 plan clients and 5 ticket clients for 8 seconds:

$ docker compose --profile load run --rm --no-deps k6
tickets  100% ok  p95 8931 ms
plan     live 50  fallback 0  failed 0

Each plan call holds a thread for three seconds, so all ten fill up, and the ticket list waits for a free one. Ten threads over three seconds is about three plan calls a second. The ticket list never calls billing, yet its p95 is almost nine seconds.

Four tools, a few numbers each

Think of a fuse box. A short in the kitchen trips the kitchen breaker and the lights stay on. The fuse box does not prevent the short. It stops it spreading. FuseBox builds its protection as plain Resilience4j objects:

@Configuration
@ConditionalOnProperty(name = "fusebox.role", havingValue = "desk")
class Resilience {

    @Bean
    CircuitBreaker billingBreaker() {
        return CircuitBreaker.of("billing", CircuitBreakerConfig.custom()
                .slidingWindowSize(10)
                .minimumNumberOfCalls(5)
                .failureRateThreshold(50)
                .waitDurationInOpenState(Duration.ofSeconds(10))
                .permittedNumberOfCallsInHalfOpenState(3)
                .build());
    }

    @Bean
    Bulkhead billingBulkhead() {
        return Bulkhead.of("billing", BulkheadConfig.custom()
                .maxConcurrentCalls(3)
                .maxWaitDuration(Duration.ZERO)
                .build());
    }

    @Bean
    Retry billingRetry() {
        return Retry.of("billing", RetryConfig.custom()
                .maxAttempts(2)
                .waitDuration(Duration.ofMillis(100))
                .ignoreExceptions(CallNotPermittedException.class,
                        BulkheadFullException.class)
                .build());
    }
}
  • The breaker watches the last ten calls. When half of them fail, it opens and calls fail at once. After ten seconds it goes half-open and lets three trial calls through. If they succeed, it closes.
  • The bulkhead lets billing use three threads at a time, with no waiting. A fourth call is refused at once, so the other seven threads stay free for tickets.
  • The retry is one more attempt after 100 ms. It ignores a refused call from the breaker or bulkhead, since retrying those only adds load.

Be careful with retries. Thirty callers with one try each is 30 calls. With two tries each it is 60, on a service that is already struggling. A timeout protects the caller, and a retry can hurt the service you are calling. Keep retries few and spaced out, and put them behind a breaker.

The circuit breaker's three states. Closed: calls go through. When 50 percent of the last ten calls fail it moves to open, where calls fail at once. After ten seconds it moves to half-open and lets three trial calls through. If they succeed it returns to closed; if they fail it opens again. CLOSEDOPENHALF-OPEN 5 of 10 fail after 10 s 3 trial calls succeed trial fails
An open breaker fails fast: no waiting and no threads held.

Wrap the call, and plan the fallback

BillingClient(FuseSettings settings, CircuitBreaker breaker,
              Bulkhead bulkhead, Retry retry) {
    var factory = new SimpleClientHttpRequestFactory();
    if (settings.protect()) {
        factory.setReadTimeout(Duration.ofMillis(500));   // never wait forever
    }
    this.http = RestClient.builder().requestFactory(factory)
            .baseUrl(settings.billingUrl()).build();
    ...
}

Map<String, Object> plan() {
    if (!settings.protect()) {
        return fetch();                        // waits as long as billing takes
    }
    Supplier<Map<String, Object>> call =
            Bulkhead.decorateSupplier(bulkhead, this::fetch);
    call = CircuitBreaker.decorateSupplier(breaker, call);
    call = Retry.decorateSupplier(retry, call);
    try {
        return call.get();
    } catch (Exception failed) {
        return Map.of("plan", "unknown", "degraded", true);   // the fallback
    }
}

The timeout comes first: half a second, then the thread is free. The call is then wrapped three times, with the bulkhead inside, the breaker around it and the retry outside. Any failure ends in the fallback, a smaller answer that still says something true: the plan is unknown right now.

$ PROTECT=true docker compose up -d desk
$ docker compose --profile load run --rm --no-deps k6
tickets  100% ok  p95 6 ms
plan     live 0   fallback 2292  failed 0
$ curl -s localhost:18320/api/breaker
{"state":"OPEN"}
$ curl -s localhost:18320/api/plan
{"degraded":true,"plan":"unknown"}

Same spike. The ticket list p95 drops from 8,931 ms to 6 ms, 2,292 plan calls got the fallback, and none failed outright. The breaker is open, so a plan call returns at once.

When billing is back, the breaker closes

$ curl -s -X DELETE localhost:18474/proxies/billing/toxics/slow
$ sleep 11; for i in 1 2 3; do curl -s localhost:18320/api/plan; echo; done; curl -s localhost:18320/api/breaker
{"plan":"pro"}
{"plan":"pro"}
{"plan":"pro"}
{"state":"CLOSED"}

After the ten-second wait, the breaker lets three trial calls through. They succeed, so it closes. No one had to restart anything.

Recap

ToolSetting hereWhat it protects
Timeout500 ms read timeoutThe caller's thread
Retry2 attempts, 100 ms apartAgainst a short blip, at the cost of extra load
Circuit breakerWindow 10, 50%, open 10 s, 3 trialsBoth sides: fails fast while billing is down
Bulkhead3 concurrent calls, no waitThe other 7 threads, for features that do not need billing
Fallbackplan: unknown, degraded: trueThe user, who still gets an answer

Try it yourself: set maxAttempts(10) and drop the breaker. Every slow call becomes ten, and the struggling service gets ten times the load. The gates that protect a service from its own callers are covered in rate limiting, backpressure and load shedding.

Keep going in Spring Boot · 40 of 99

Previous
Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
Next post
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work

Three gates in a small Spring Boot service, RateGate. A Bucket4j bucket per tenant and endpoint in Redis lets 5 calls through and answers the rest with 429 and Retry-After: 5. Four workers and a line of eight answer 12 of 20 calls and refuse 8 at once. Shedding AI summaries takes ticket calls from 6% to 100% success under a spike.

On this page

  • One slow call takes every thread
  • Four tools, a few numbers each
  • Wrap the call, and plan the fallback
  • When billing is back, the breaker closes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.