Building Scalable Microservices with Spring Boot 3
Why Spring Boot 3 fundamentally changes how your services behave under load—50-80% faster startup, dramatically lower memory, and observability built into the framework. A deep dive into GraalVM native images, the Observation API, and patterns that actually scale.
- Author
- Eslam SifeEldin, Principal Software Engineer
- Published
- Reading time
- 18 min
- Topic
- Microservices
Your Spring Boot 2.x services are running fine. They handle traffic, they pass tests, and nobody's pager is going off at 3 AM. So why should you care about Spring Boot 3?
Here's the uncomfortable truth: Spring Boot 2.x reached end of commercial support in August 2024. But security patches aside, the real reason to migrate isn't compliance—it's that Spring Boot 3 fundamentally changes how your services behave under load. We're talking about 50-80% reduction in startup time, dramatically lower memory footprint, and observability that's actually built into the framework instead of bolted on as an afterthought.
If you're running microservices at scale—or planning to—this isn't a nice-to-have upgrade. It's the difference between spinning up 10 instances in 30 seconds versus 5 minutes.
The Java 17 Baseline: More Than a Version Bump
Spring Boot 3 requires Java 17 as the minimum. This isn't arbitrary gatekeeping—it's a strategic decision that unlocks performance characteristics you simply can't get on older JVMs.
Records and Pattern Matching Reduce Allocation Pressure
Java 17 brings Records to the table, and they're not just syntactic sugar. In a microservice context, you're constantly serializing and deserializing DTOs. Records are implicitly final, their fields are implicitly final, and the JVM knows this at compile time.
// Before: Mutable POJO with defensive copying overhead
public class OrderEvent {
private String orderId;
private BigDecimal amount;
private Instant timestamp;
// Constructor, getters, setters, equals, hashCode, toString...
// Plus defensive copies if you want immutability
}
// After: Immutable by design, JVM-optimized
public record OrderEvent(
String orderId,
BigDecimal amount,
Instant timestamp
) {}The JVM's escape analysis works better with Records. When the JIT compiler can prove your OrderEvent doesn't escape the current method, it can allocate it on the stack instead of the heap. At 10,000 requests per second, that's millions of avoided GC allocations per minute.
Sealed Classes Enable Smarter Service Contracts
Pattern matching with sealed classes lets you define exhaustive hierarchies that the compiler enforces:
public sealed interface PaymentResult
permits PaymentSuccess, PaymentFailure, PaymentPending {
}
public record PaymentSuccess(String transactionId, Instant processedAt)
implements PaymentResult {}
public record PaymentFailure(String errorCode, String message)
implements PaymentResult {}
public record PaymentPending(String trackingId, Duration estimatedWait)
implements PaymentResult {}
// In your service layer - compiler guarantees exhaustiveness
public ResponseEntity<?> handlePayment(PaymentResult result) {
return switch (result) {
case PaymentSuccess s -> ResponseEntity.ok(s);
case PaymentFailure f -> ResponseEntity.badRequest().body(f);
case PaymentPending p -> ResponseEntity.accepted().body(p);
// No default needed - compiler knows this is exhaustive
};
}This matters for scalability because exhaustive matching eliminates entire categories of runtime errors. Fewer errors mean fewer retries, fewer circuit breaker trips, and more predictable resource consumption.
GraalVM Native Images: The Real Game Changer
Let's be direct: if you're running microservices on Kubernetes and you're not at least evaluating native images, you're leaving money on the table.
Traditional JVM startup involves class loading, bytecode verification, JIT warm-up, and heap initialization. A typical Spring Boot 2.x service takes 5-15 seconds to become ready. That's an eternity when Kubernetes is trying to scale your deployment from 2 pods to 20 during a traffic spike.
What Native Compilation Actually Does
GraalVM's native-image tool performs Ahead-of-Time (AOT) compilation. It analyzes your entire application at build time, determines what code is actually reachable, and compiles it directly to machine code. No JVM, no class loading, no JIT warm-up.
Spring Boot 3 includes first-class support via Spring AOT:
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<buildArgs>
<buildArg>--enable-preview</buildArg>
<buildArg>-H:+ReportExceptionStackTraces</buildArg>
</buildArgs>
</configuration>
</plugin>Build with:
./mvnw -Pnative native:compileThe Numbers Don't Lie
Here's what I measured on a real-world order processing service (16 REST endpoints, PostgreSQL, Redis, Kafka):
| Metric | JVM (Spring Boot 3) | Native Image |
|---|---|---|
| Startup time | 4.2 seconds | 0.08 seconds |
| Memory at idle | 412 MB | 89 MB |
| Memory under load | 680 MB | 156 MB |
| First request latency | 230ms | 12ms |
That 0.08-second startup isn't a typo. Your service is ready before Kubernetes even finishes its readiness probe.
The Trade-offs (Because There Always Are Some)
Native images aren't free:
-
Build times increase dramatically. That same service takes 45 seconds to build as a JAR but 4-6 minutes as a native image. Your CI pipeline needs to account for this.
-
Reflection requires configuration. GraalVM can't see runtime reflection, so you need to declare it explicitly. Spring Boot 3's AOT engine handles most of this automatically, but custom reflection-heavy code needs hints:
@RegisterReflectionForBinding(ExternalApiResponse.class)
public class ExternalApiClient {
// GraalVM now knows to include reflection metadata for ExternalApiResponse
}- Peak throughput can be lower. The JIT compiler optimizes hot paths over time. Native images don't have this. For long-running, throughput-critical services, you might see 10-15% lower peak RPS compared to a fully warmed JVM.
When to use native images: Serverless functions, scale-to-zero scenarios, services with frequent cold starts, memory-constrained environments.
When to avoid native images: Throughput-critical services that run 24/7, applications with heavy reflection (like some ORM configurations), when build time is a bottleneck.
The Observation API: Observability That Doesn't Suck
Here's a pattern I've seen in too many codebases:
// The "observability" anti-pattern
public Order processOrder(OrderRequest request) {
long start = System.currentTimeMillis();
try {
meterRegistry.counter("orders.processed").increment();
Span span = tracer.spanBuilder("processOrder").startSpan();
try (Scope scope = span.makeCurrent()) {
// Actual business logic buried somewhere in here
Order order = doTheActualWork(request);
span.setAttribute("orderId", order.getId());
return order;
} finally {
span.end();
}
} finally {
meterRegistry.timer("orders.duration")
.record(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
}
}Your business logic is drowning in observability boilerplate. It's fragile, it's repetitive, and developers start skipping it because it's tedious.
Spring Boot 3 introduces the Observation API via Micrometer, and it changes everything.
One Annotation, Complete Observability
@Observed(
name = "order.processing",
contextualName = "process-order",
lowCardinalityKeyValues = {"orderType", "standard"}
)
public Order processOrder(OrderRequest request) {
// Just your business logic. That's it.
return orderRepository.save(
Order.from(request)
.withStatus(OrderStatus.CONFIRMED)
.build()
);
}That single @Observed annotation automatically generates:
- A timer metric (
order.processing) - A span for distributed tracing
- Error tracking with proper exception propagation
- Low-cardinality tags for metric aggregation
Configuration-Driven Backend Selection
The beauty is that your code doesn't know or care whether you're using Prometheus, Datadog, Jaeger, or Zipkin:
# application.yml
management:
tracing:
sampling:
probability: 1.0 # Sample everything in dev, tune for prod
observations:
key-values:
service: order-service
environment: ${SPRING_PROFILES_ACTIVE:local}@Configuration
public class ObservabilityConfig {
@Bean
public ObservationHandler<Observation.Context> propagatingHandler(Tracer tracer) {
return new PropagatingReceiverTracingObservationHandler<>(tracer, new W3CPropagation());
}
}Switch from Jaeger to Zipkin? Change a dependency, not your code.
Custom Observations for Critical Paths
For fine-grained control over what gets observed:
@Component
public class PaymentProcessor {
private final ObservationRegistry observationRegistry;
public PaymentResult processPayment(Payment payment) {
return Observation.createNotStarted("payment.processing", observationRegistry)
.lowCardinalityKeyValue("paymentMethod", payment.getMethod().name())
.lowCardinalityKeyValue("currency", payment.getCurrency())
.highCardinalityKeyValue("paymentId", payment.getId()) // High cardinality = traces only
.observe(() -> {
// Your payment logic
return gateway.process(payment);
});
}
}The distinction between low-cardinality (good for metrics, limited values like "CREDIT_CARD", "PAYPAL") and high-cardinality (good for traces, unlimited values like payment IDs) is built into the API. You're guided toward observability best practices instead of accidentally creating metric explosions.
Scaling Patterns That Actually Work
Let's talk architecture. Spring Boot 3's features enable patterns that were painful or impossible before.
Pattern 1: Virtual Threads for I/O-Bound Services
Java 21 brings virtual threads (Project Loom), and Spring Boot 3.2+ supports them out of the box:
spring:
threads:
virtual:
enabled: trueThat's it. Your entire application now uses virtual threads. But here's where it gets interesting for scalability:
@RestController
public class AggregationController {
private final List<ExternalService> services;
@GetMapping("/aggregate")
public AggregatedResponse aggregate() {
// With virtual threads, this doesn't block platform threads
return services.parallelStream()
.map(ExternalService::fetchData)
.reduce(AggregatedResponse::merge)
.orElse(AggregatedResponse.empty());
}
}With platform threads, 1000 concurrent requests waiting on I/O would require 1000 OS threads. With virtual threads, you can have millions of concurrent operations on a handful of platform threads. The thread-per-request model becomes viable again without the resource explosion.
Pattern 2: Structured Concurrency for Partial Failure Handling
When aggregating from multiple services, you need to handle partial failures gracefully:
public record ProductDetails(
Product product,
Optional<Inventory> inventory,
Optional<Pricing> pricing,
Optional<List<Review>> reviews
) {}
public ProductDetails getProductDetails(String productId)
throws InterruptedException, ExecutionException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// These all run concurrently
Subtask<Product> productTask = scope.fork(() ->
productService.getProduct(productId));
Subtask<Inventory> inventoryTask = scope.fork(() ->
inventoryService.getInventory(productId));
Subtask<Pricing> pricingTask = scope.fork(() ->
pricingService.getPricing(productId));
Subtask<List<Review>> reviewsTask = scope.fork(() ->
reviewService.getReviews(productId));
scope.join();
// Product is required, others are optional
Product product = productTask.get(); // Throws if failed
return new ProductDetails(
product,
getIfSuccessful(inventoryTask),
getIfSuccessful(pricingTask),
getIfSuccessful(reviewsTask)
);
}
}
private <T> Optional<T> getIfSuccessful(Subtask<T> task) {
return task.state() == Subtask.State.SUCCESS
? Optional.of(task.get())
: Optional.empty();
}This pattern gives you:
- Concurrent execution of all calls
- Automatic cancellation if the required call fails
- Graceful degradation for optional data
- No thread pool tuning required
Migration Reality Check
I've migrated three production systems from Spring Boot 2.7 to 3.x. Here's what actually matters:
The Jakarta Namespace Change
Every javax.* import becomes jakarta.*. This sounds trivial until you realize it affects:
- Every servlet-related class
- Every persistence annotation
- Every validation constraint
- Every transaction annotation
// Before
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import javax.servlet.http.HttpServletRequest;
// After
import jakarta.persistence.Entity;
import jakarta.validation.constraints.NotNull;
import jakarta.servlet.http.HttpServletRequest;Use OpenRewrite to automate this. The Spring team provides official recipes:
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<version>5.34.0</version>
<configuration>
<activeRecipes>
<recipe>org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3</recipe>
</activeRecipes>
</configuration>
</plugin>Run ./mvnw rewrite:run and review the changes. It handles 80% of the migration automatically.
Properties That Changed
Spring Boot 3 renamed or removed several properties. These will silently do nothing if you don't update them:
# Before (Spring Boot 2.x)
spring:
redis:
host: localhost
# After (Spring Boot 3.x)
spring:
data:
redis:
host: localhostThe Spring Boot 3 migration guide (referenced in the official documentation) has a complete list of property changes. Audit your application.yml files against it.
Third-Party Library Compatibility
Some libraries aren't ready for Jakarta namespace or Java 17. Before migrating:
- Check that your ORM tools support Jakarta Persistence 3.x
- Verify your testing libraries work with JUnit 5.9+
- Ensure your security libraries support Spring Security 6.x
The Bottom Line
Spring Boot 3 isn't just a version upgrade—it's a platform shift that fundamentally improves how microservices scale. The Java 17 baseline gives you better runtime characteristics. Native images give you sub-second startup and minimal memory. The Observation API makes observability a first-class citizen instead of an afterthought.
Should you migrate? If you're building new services, absolutely use Spring Boot 3. If you're maintaining existing services, start planning your migration now—not because Spring Boot 2.x is broken, but because Spring Boot 3.x is measurably better at scale.
The investment in migration pays dividends every time Kubernetes scales your pods, every time you debug a production issue with proper traces, and every time your services cold-start faster than your monitoring can detect the restart.
References:
- Spring Boot 3.0 Migration Guide (Spring Official Documentation)
- GraalVM Native Image Reference (GraalVM Documentation)
- Micrometer Observation API (Micrometer Documentation)
- JEP 444: Virtual Threads (OpenJDK)
- OpenRewrite Spring Boot 3 Migration Recipes (OpenRewrite Documentation)
Related writing
- Event-Driven Architecture with Apache Kafka10 min · System Design
Working on a system like this?
I take on architecture consulting, contract engineering and full projects. Tell me what the system does today and what it needs to do next.
I usually reply within a day