Skip to content

Commit 0dc5355

Browse files
committed
Add Microservices Bulkhead pattern implementation
- Implements resource isolation with dedicated thread pools - Demonstrates fail-fast behavior under load - Fixes #3228
1 parent ede37bd commit 0dc5355

File tree

8 files changed

+773
-0
lines changed

8 files changed

+773
-0
lines changed

microservices-bulkhead/README.md

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
---
2+
title: "Bulkhead Pattern in Java: Isolating Resources for Resilient Microservices"
3+
shortTitle: Bulkhead
4+
description: "Learn how the Bulkhead pattern in Java isolates critical system resources to prevent cascade failures in microservices. Includes real-world examples, code demonstrations, and best practices for building resilient distributed systems."
5+
category: Resilience
6+
language: en
7+
tag:
8+
- Resilience
9+
- Fault tolerance
10+
- Microservices
11+
- Performance
12+
- Scalability
13+
- Thread management
14+
---
15+
16+
## Also known as
17+
18+
* Resource Isolation Pattern
19+
* Partition Pattern
20+
21+
## Intent of Bulkhead Design Pattern
22+
23+
The Bulkhead pattern isolates critical system resources for each service or component to prevent failures or heavy load in one part of the system from cascading and degrading the entire application. By partitioning resources—often via separate thread pools or connection pools—the system ensures other services remain operational even if one service becomes overloaded or fails.
24+
25+
## Detailed Explanation of Bulkhead Pattern with Real-World Examples
26+
27+
Real-world example
28+
29+
> Consider a modern cruise ship with multiple watertight compartments (bulkheads). If one compartment is breached and starts flooding, the bulkheads prevent water from spreading to other compartments, keeping the ship afloat. Similarly, in software systems, the Bulkhead pattern creates isolated resource pools for different services. If one service experiences issues (like a slow external API or heavy load), it only affects its dedicated resources, while other services continue operating normally with their own resource pools.
30+
31+
In plain words
32+
33+
> The Bulkhead pattern partitions system resources into isolated pools so that failures in one area don't consume all available resources and bring down the entire system.
34+
35+
## Programmatic Example of Bulkhead Pattern in Java
36+
37+
The Bulkhead pattern implementation demonstrates resource isolation using dedicated thread pools for different services. Here we have a `UserService` handling critical user requests and a `BackgroundService` handling non-critical tasks.
38+
39+
First, let's look at the base `BulkheadService` class that provides resource isolation:
40+
41+
```
42+
public abstract class BulkheadService {
43+
private static final Logger LOGGER = LoggerFactory.getLogger(BulkheadService.class);
44+
45+
protected final ThreadPoolExecutor executor;
46+
protected final String serviceName;
47+
48+
protected BulkheadService(String serviceName, int maxPoolSize, int queueCapacity) {
49+
this.serviceName = serviceName;
50+
51+
// Create thread pool with bounded queue for resource isolation
52+
this.executor = new ThreadPoolExecutor(
53+
maxPoolSize,
54+
maxPoolSize,
55+
60L,
56+
TimeUnit.SECONDS,
57+
new ArrayBlockingQueue<>(queueCapacity),
58+
new ThreadPoolExecutor.AbortPolicy() // fail-fast when full
59+
);
60+
61+
LOGGER.info("Created {} with {} threads and queue capacity {}",
62+
serviceName, maxPoolSize, queueCapacity);
63+
}
64+
65+
public boolean submitTask(Task task) {
66+
try {
67+
executor.execute(() -> processTask(task));
68+
LOGGER.info("[{}] Task '{}' submitted successfully", serviceName, task.getName());
69+
return true;
70+
} catch (RejectedExecutionException e) {
71+
LOGGER.warn("[{}] Task '{}' REJECTED - bulkhead is full", serviceName, task.getName());
72+
handleRejectedTask(task);
73+
return false;
74+
}
75+
}
76+
}
77+
```
78+
79+
The `UserService` handles critical user-facing requests with dedicated resources:
80+
81+
```
82+
public class UserService extends BulkheadService {
83+
private static final int DEFAULT_QUEUE_CAPACITY = 10;
84+
85+
public UserService(int maxThreads) {
86+
super("UserService", maxThreads, DEFAULT_QUEUE_CAPACITY);
87+
}
88+
}
89+
```
90+
91+
The `BackgroundService` handles non-critical background tasks with its own isolated resources:
92+
93+
```
94+
public class BackgroundService extends BulkheadService {
95+
private static final int DEFAULT_QUEUE_CAPACITY = 20;
96+
97+
public BackgroundService(int maxThreads) {
98+
super("BackgroundService", maxThreads, DEFAULT_QUEUE_CAPACITY);
99+
}
100+
}
101+
```
102+
103+
Here's the demonstration showing how the Bulkhead pattern prevents cascade failures:
104+
105+
```
106+
public class App {
107+
public static void main(String[] args) {
108+
BulkheadService userService = new UserService(3);
109+
BulkheadService backgroundService = new BackgroundService(2);
110+
111+
// Overload background service with many tasks
112+
for (int i = 1; i <= 10; i++) {
113+
Task task = new Task("Heavy-Background-Job-" + i, TaskType.BACKGROUND_PROCESSING, 2000);
114+
backgroundService.submitTask(task);
115+
}
116+
117+
// User service remains responsive despite background service overload
118+
for (int i = 1; i <= 3; i++) {
119+
Task task = new Task("Critical-User-Request-" + i, TaskType.USER_REQUEST, 300);
120+
boolean accepted = userService.submitTask(task);
121+
LOGGER.info("User request {} accepted: {}", i, accepted);
122+
}
123+
}
124+
}
125+
```
126+
127+
Program output:
128+
129+
```
130+
[BackgroundService] Task 'Heavy-Background-Job-1' submitted successfully
131+
[BackgroundService] Task 'Heavy-Background-Job-2' submitted successfully
132+
[BackgroundService] Task 'Heavy-Background-Job-3' REJECTED - bulkhead is full
133+
...
134+
[UserService] Task 'Critical-User-Request-1' submitted successfully
135+
[UserService] Task 'Critical-User-Request-2' submitted successfully
136+
[UserService] Task 'Critical-User-Request-3' submitted successfully
137+
User request 1 accepted: true
138+
User request 2 accepted: true
139+
User request 3 accepted: true
140+
```
141+
142+
The output demonstrates that even when the background service is overloaded and rejecting tasks, the user service continues to accept and process requests successfully due to resource isolation.
143+
144+
## When to Use the Bulkhead Pattern in Java
145+
146+
* When building microservices architectures where service failures should not cascade
147+
* When different operations have varying criticality levels (e.g., user-facing vs. background tasks)
148+
* When external dependencies (databases, APIs) might become slow or unavailable
149+
* When you need to guarantee minimum service levels for critical operations
150+
* In high-throughput systems where resource exhaustion in one area could impact other services
151+
152+
## Real-World Applications of Bulkhead Pattern in Java
153+
154+
* Netflix's Hystrix library implements bulkheads using thread pool isolation
155+
* Resilience4j provides bulkhead implementations for Java applications
156+
* AWS Lambda functions run in isolated execution environments (bulkheads)
157+
* Kubernetes resource limits and quotas implement bulkhead principles
158+
* Database connection pools per service in microservices architectures
159+
160+
## Benefits and Trade-offs of Bulkhead Pattern
161+
162+
Benefits:
163+
164+
* Prevents cascade failures across services
165+
* Improves system resilience and availability
166+
* Provides predictable degradation under load
167+
* Enables independent scaling of different services
168+
* Facilitates easier capacity planning and monitoring
169+
170+
Trade-offs:
171+
172+
* Increased resource overhead (multiple thread pools)
173+
* More complex configuration and tuning
174+
* Potential for resource underutilization if pools are too large
175+
* Requires careful capacity planning for each bulkhead
176+
* May increase overall latency due to queuing
177+
178+
## Related Java Design Patterns
179+
180+
* [Circuit Breaker](https://java-design-patterns.com/patterns/circuit-breaker/): Often used together with Bulkhead; Circuit Breaker stops calling failing services while Bulkhead limits resources
181+
* [Retry](https://java-design-patterns.com/patterns/retry/): Can be combined with Bulkhead for transient failure handling
182+
* [Throttling](https://java-design-patterns.com/patterns/throttling/): Similar goal of resource management but focuses on rate limiting rather than isolation
183+
* [Load Balancer](https://java-design-patterns.com/patterns/load-balancer/): Works at request distribution level while Bulkhead works at resource isolation level
184+
185+
## References and Credits
186+
187+
* [Release It!: Design and Deploy Production-Ready Software](https://amzn.to/3Uul4kF) - Michael T. Nygard
188+
* [Microservices Patterns: With examples in Java](https://amzn.to/3UyWD5O) - Chris Richardson
189+
* [Building Microservices: Designing Fine-Grained Systems](https://amzn.to/3RYRz96) - Sam Newman
190+
* [Resilience4j Documentation - Bulkhead](https://resilience4j.readme.io/docs/bulkhead)
191+
* [Microsoft Azure Architecture - Bulkhead Pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/bulkhead)
192+
* [Microservices.io - Bulkhead Pattern](https://microservices.io/patterns/reliability/bulkhead.html)

microservices-bulkhead/pom.xml

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
~
4+
~ This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
5+
~
6+
~ The MIT License
7+
~ Copyright © 2014-2025 Ilkka Seppälä
8+
~
9+
~ Permission is hereby granted, free of charge, to any person obtaining a copy
10+
~ of this software and associated documentation files (the "Software"), to deal
11+
~ in the Software without restriction, including without limitation the rights
12+
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
~ copies of the Software, and to permit persons to whom the Software is
14+
~ furnished to do so, subject to the following conditions:
15+
~
16+
~ The above copyright notice and this permission notice shall be included in
17+
~ all copies or substantial portions of the Software.
18+
~
19+
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
~ THE SOFTWARE.
26+
~
27+
-->
28+
<project xmlns="http://maven.apache.org/POM/4.0.0"
29+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
30+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
31+
<modelVersion>4.0.0</modelVersion>
32+
33+
<parent>
34+
<groupId>com.iluwatar</groupId>
35+
<artifactId>java-design-patterns</artifactId>
36+
<version>1.26.0-SNAPSHOT</version>
37+
</parent>
38+
39+
<artifactId>bulkhead</artifactId>
40+
<packaging>jar</packaging>
41+
42+
<name>Bulkhead</name>
43+
<description>
44+
The Bulkhead pattern isolates critical system resources for each service or component
45+
to prevent failures or heavy load in one part from cascading and degrading the entire system.
46+
By partitioning resources via separate thread pools, the system ensures other services
47+
remain operational even if one service becomes overloaded or fails.
48+
</description>
49+
50+
<properties>
51+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
52+
</properties>
53+
54+
<dependencies>
55+
<!-- SLF4J API for logging -->
56+
<dependency>
57+
<groupId>org.slf4j</groupId>
58+
<artifactId>slf4j-api</artifactId>
59+
</dependency>
60+
61+
<!-- Logback for logging implementation -->
62+
<dependency>
63+
<groupId>ch.qos.logback</groupId>
64+
<artifactId>logback-classic</artifactId>
65+
<scope>runtime</scope>
66+
</dependency>
67+
68+
<!-- Lombok for reducing boilerplate code -->
69+
<dependency>
70+
<groupId>org.projectlombok</groupId>
71+
<artifactId>lombok</artifactId>
72+
<scope>provided</scope>
73+
</dependency>
74+
75+
<!-- JUnit Jupiter for testing -->
76+
<dependency>
77+
<groupId>org.junit.jupiter</groupId>
78+
<artifactId>junit-jupiter-engine</artifactId>
79+
<scope>test</scope>
80+
</dependency>
81+
82+
<!-- JUnit Jupiter Params for parameterized tests -->
83+
<dependency>
84+
<groupId>org.junit.jupiter</groupId>
85+
<artifactId>junit-jupiter-params</artifactId>
86+
<scope>test</scope>
87+
</dependency>
88+
89+
<!-- Mockito for mocking in tests -->
90+
<dependency>
91+
<groupId>org.mockito</groupId>
92+
<artifactId>mockito-core</artifactId>
93+
<scope>test</scope>
94+
</dependency>
95+
96+
<!-- AssertJ for fluent assertions in tests -->
97+
<dependency>
98+
<groupId>org.assertj</groupId>
99+
<artifactId>assertj-core</artifactId>
100+
<scope>test</scope>
101+
</dependency>
102+
</dependencies>
103+
104+
<build>
105+
<plugins>
106+
<!-- Maven Compiler Plugin -->
107+
<plugin>
108+
<groupId>org.apache.maven.plugins</groupId>
109+
<artifactId>maven-compiler-plugin</artifactId>
110+
</plugin>
111+
112+
<!-- Maven Surefire Plugin for running tests -->
113+
<plugin>
114+
<groupId>org.apache.maven.plugins</groupId>
115+
<artifactId>maven-surefire-plugin</artifactId>
116+
</plugin>
117+
118+
<!-- Spotless Plugin for code formatting -->
119+
<plugin>
120+
<groupId>com.diffplug.spotless</groupId>
121+
<artifactId>spotless-maven-plugin</artifactId>
122+
</plugin>
123+
124+
<!-- Maven Checkstyle Plugin -->
125+
<plugin>
126+
<groupId>org.apache.maven.plugins</groupId>
127+
<artifactId>maven-checkstyle-plugin</artifactId>
128+
</plugin>
129+
130+
<!-- PMD Plugin for static code analysis -->
131+
<plugin>
132+
<groupId>org.apache.maven.plugins</groupId>
133+
<artifactId>maven-pmd-plugin</artifactId>
134+
</plugin>
135+
136+
<!-- SpotBugs Plugin for bug detection -->
137+
<plugin>
138+
<groupId>com.github.spotbugs</groupId>
139+
<artifactId>spotbugs-maven-plugin</artifactId>
140+
</plugin>
141+
</plugins>
142+
</build>
143+
144+
</project>

0 commit comments

Comments
 (0)