Your Spring Boot API is slow. Not because of bad code. Because of invisible garbage. A simple request like GET /api/users/123 looks harmless. But Spring Boot creates a storm of temporary objects you never see: → Tomcat builds request/response objects → Spring Security creates SecurityContext → Filters wrap everything in decorators → Hibernate creates lazy-load proxies → Dirty checking snapshots entity state → Jackson builds serialization objects → @Transactional wraps services in proxies You wrote 15 lines. The framework created thousands of objects. At 100 RPS? Fine. At 1,000 RPS? Disaster. Young Gen fills every second GC runs constantly p99 latency spikes CPU burns on cleanup, not business logic No crash. No exception. Just mysteriously slow performance. ━━━━━━━━━━━━━━━━ How I reduce object creation: Return DTOs, not entities Use @Transactional(readOnly = true) for reads Use log placeholders: log.info("User {}", id) Prefer primitives (int vs Integer) in hot paths Avoid streams/maps in performance-critical loops Tune JVM Young Gen size Profile with Java Flight Recorder ━━━━━━━━━━━━━━━━ The real performance truth: The fastest code isn't code that executes the fastest. It's code that creates the least garbage. Master this, and your APIs will scale. What's your go-to optimization for high-traffic Spring Boot apps? #SpringBoot #Java #Microservices #BackendDevelopment #SoftwareArchitecture
Spring Boot Performance Optimization: Reduce Garbage Creation
More Relevant Posts
-
Most slow Spring Boot apps have the same problem. It's not the database. It's how you ask it. After years debugging production performance, I see the same pattern over and over: The N+1 query problem. You fetch a list of orders. Looks fine. Then you loop through them and access order.getCustomer(). Hibernate happily fires one extra query per order. 100 orders → 101 queries. Your endpoint goes from 50ms to 4 seconds. Your database CPU climbs. Nobody understands why. The trap is that the code looks clean. Lazy loading is doing exactly what it said it would. The framework isn't broken. The mental model is. What actually fixes it: - JOIN FETCH for predictable, single-use queries - @EntityGraph for reusable fetch plans - Batch fetching (hibernate.default_batch_fetch_size) when you need lazy but not crazy - DTO projections when you don't need the full entity at all ⚠️ The mistake most teams make is enabling spring.jpa.show-sql=true, seeing 5 queries per request, and shrugging. Five becomes fifty under load. Fifty becomes the incident. The fix is not "tune the database." The fix is reading what your ORM is actually doing. Hibernate is not slow. Most Hibernate code is. What's the worst N+1 you've seen in production? #Java #SpringBoot #Backend #Hibernate #Performance #SoftwareEngineering
To view or add a comment, sign in
-
-
Is FetchType.EAGER silently killing your performance? 🚨 One mistake I’ve seen repeatedly in Spring Boot applications is overusing EAGER fetching. Looks harmless… until it hits production. The problem 👇 Every time you fetch a parent entity, Hibernate also loads the entire child collection. Now imagine: → A user with 5,000 orders → A department with 50,000 employees Your “simple query” just became a massive memory load. This doesn’t just slow things down… it stresses your entire JVM. What I follow instead 👇 ✔ Default to LAZY ✔ Use JOIN FETCH when needed ✔ Use @EntityGraph for controlled fetching Your entity design is not just structure. It’s a performance decision. Better to write 1 extra query… than load 10,000 unnecessary records. Curious to hear from other devs 👇 Do you treat FetchType.EAGER as a bad practice? Or still use it in some cases? #Java #SpringBoot #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #Performance #TechDiscussion
To view or add a comment, sign in
-
-
Was working on a Spring Boot REST API the other day. Everything looked fine entity class, repository, controller all set up. But two fields, createdAt and updatedAt, were coming back null in every response. Spent time checking the constructor, the DTO mapping, the database config. Turns out I just needed two annotations: @CreationTimestamp → auto-sets the time when record is created @UpdateTimestamp → auto-updates the time on every save Two lines. That's it. Hibernate handles everything behind the scenes you don't set these manually. One more thing I'd missed without @JsonFormat, Java's Timestamp serializes weirdly in JSON. Add this and it formats cleanly: @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") Small things. But they'll silently break your API if you miss them. #Java #SpringBoot #Backend #LearningInPublic #HibernateJPA
To view or add a comment, sign in
-
-
Java Spring Boot Annotations in a Nutshell https://lnkd.in/g7BmyE3E A technical overview of the essential Java Spring Boot Annotations, serving as a comprehensive "nutshell" guide for modern backend development. As Spring Boot continues to dominate the enterprise ecosystem, mastering its annotation-driven configuration is critical for building scalable, decoupled, and maintainable microservices. => Core Framework Annotations: Analyzing @SpringBootApplication, @Component, and @Bean for managing application context and dependency injection. => Web and REST Integration: Demonstrating the use of @RestController, @RequestMapping, and @PathVariable to streamline API development. => Data and Configuration: Leveraging @Service, @Repository, and @Value to enforce clean architectural layers and externalize properties. #codechallenge #programming #CODE #Coding #code #programmingtips #java #JAVAFullStack #spring #springframework #Springboot #springbootdeveloper #Maven #gradle #annotations #controller #service #dependencyInjection
To view or add a comment, sign in
-
File Uploads and Retrieval in Spring Boot Master file management in modern web applications by exploring File Uploads and Retrieval in Spring Boot. Handling binary data is a core requirement for enterprise systems, and this guide provides a deep dive into building a robust solution using REST controllers and the MultipartFile interface. Following a "core-to-shell" approach, you’ll learn to integrate foundational Java NIO operations with high-level Spring APIs to create a seamless bridge between raw disk storage and your frontend. Discover how to implement secure uploads and efficient file fetching while maintaining a clean, scalable microservices architecture. => Multipart Management: Efficiently process file streams with Spring Boot. => Java NIO Mastery: Use modern I/O for high-performance file handling. => RESTful Fetch: Implement endpoints for secure content retrieval. https://lnkd.in/gyQvP5QA #SpringBoot #spring #springframework #springbootdeveloper #Maven #Java #java #JAVAFullStack #RESTAPI #Microservices #BackendDev #JavaNIO #FileUpload #WebDevelopment #CodingTutorial #codechallenge #programming #CODE #Coding #code #programmingtips
To view or add a comment, sign in
-
Spring Boot's OSIV default turns your JSON serializer into a hidden query engine I'm building a personal finance platform with Spring Boot 3.5 + Java 21. The first thing I disabled was Open Session in View. Spring Boot ships with spring.jpa.open-in-view=true. That means Hibernate keeps a database connection open through the entire HTTP request - including JSON serialization. When Jackson walks your entity graph to build a response, every uninitialized lazy relationship triggers a database query. Your serializer is now executing SQL. In a load test with HikariCP's default pool of 10 connections and around 150 concurrent requests, this is where things break. Each request holds a connection for the full request lifecycle instead of just the service layer. The pool exhausts, threads queue up, and response times spike. The tricky part is that it works fine in dev when you're the only user. Disabling OSIV forces you to think about what data you actually need. You fetch it explicitly in the service layer with JOIN FETCH or projections, map it to a DTO, and the connection goes back to the pool before serialization even starts. It's more code upfront but the data flow becomes visible instead of hidden behind proxy magic. The second thing I changed was ddl-auto. Hibernate's update mode can generate schema changes automatically, but it can't rename columns, drop unused indexes, or migrate data. It produces a schema that looks right but drifts from what you intended. I use validate with Flyway migrations instead - every schema change is an explicit, versioned SQL file. If the code and the database disagree, the app refuses to start rather than silently diverging. These two defaults share the same problem. They hide complexity that surfaces as production issues. OSIV hides query execution. ddl-auto update hides schema drift. In both cases, making the behavior explicit costs more effort early but removes an entire class of debugging later. #SpringBoot #Java #BuildInPublic #BackendDevelopment
To view or add a comment, sign in
-
Most Spring Boot apps don’t have performance problems… They have invisible problems 🔴 Built with Spring Boot + Hibernate, everything looks clean: ✔️ Controllers ✔️ Services ✔️ Repositories But behind the scenes: → 1 API call → 30+ queries → Duplicate executions → N+1 issues And you don’t notice… until production slows down. 📉 So I built something to expose it. 🛡️ Query Guard A Spring Boot starter that shows exactly what your database is doing per request. What it gives you: → Detects N+1 queries → Finds duplicate queries → Shows query execution flow (like tracing) → Works out-of-the-box with Prometheus + Grafana + Loki ⚡ Quick facts: ✅ Published on Maven Central ⚙️ Works with Spring Boot 3 & 4 🔌 Plug & play (no code changes) 📎 Inbuilt Dashboard & Query Explorer 🧪 I have built a demo app With intentional: → N+1 issues → Duplicate queries 👉 So you can see the problem, not just read about it Demo: https://lnkd.in/gvtAnPHw Starter: https://lnkd.in/gC5hKjg3 Most tools tell you: ❌ “Your API is slow” This tells you: ✅ Why ✅ Where ✅ How often Would love your feedbacks... #SpringBoot #Java #Backend #Performance #Hibernate #OpenSource #PoojithaIrosha
To view or add a comment, sign in
-
-
🧬 Spring Boot – Understanding API Responses Today I explored how Spring Boot sends data from backend to frontend. 🧠 Key Learnings: ✔️ Returning a Java object automatically converts it to JSON ✔️ Spring Boot uses Jackson internally for this conversion ✔️ "@ResponseBody" ensures data is sent directly as response 💡 Best Practice: 👉 Using "@RestController" simplifies everything (Combination of @Controller + @ResponseBody) ✔️ Explored different return types: • Object • List • String • ResponseEntity (for better control over status & response) 🔁 API Flow: Request → Controller → Service → Return Object → JSON Response → Client 💻DSA Practice: • Even/Odd check using modulus • Sum of first N numbers (optimized using formula) ✨ Understanding how backend responses work is key to building real-world REST APIs. #SpringBoot #Java #BackendDevelopment #RESTAPI #WebDevelopment #DSA #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
⚠️ Hot Reload in Spring Boot Isn’t Magic. It’s ClassLoader Isolation. When you change code and see: 👉 App restarts in seconds 👉 No full JVM restart What’s really happening? 1️⃣ Two ClassLoaders — The Core Idea Spring Boot DevTools splits your app into: Base ClassLoader → dependencies (stable) Restart ClassLoader → your application code (changing) 2️⃣ Why This Matters Dependencies (like Spring, Hibernate): Loaded once Heavy to reload Rarely change Your code: Changes frequently Needs fast reload So only your code is reloaded. 3️⃣ What Happens on Code Change You modify a .class file DevTools detects change (file watcher) Discards Restart ClassLoader Creates a new one Reloads your classes Base ClassLoader stays untouched 4️⃣ Why It’s Faster Than Full Restart Without DevTools: JVM restarts All classes reloaded Framework reinitialized With DevTools: Only your classes reload Dependencies reused Startup drastically reduced 5️⃣ What Actually Gets Restarted? Spring ApplicationContext Beans created again Config reloaded But: 👉 JVM process stays alive 👉 Core libraries remain loaded 6️⃣ Common Gotcha (Very Important) Static state survives in Base ClassLoader. Example: static Map cache = new HashMap(); If loaded by base loader: It won’t reset after reload Leads to weird bugs 7️⃣ Why Some Changes Don’t Reload DevTools won’t reload when: Dependency JAR changes Config outside classpath changes Native resources updated Requires full restart 8️⃣ Comparison With Other Tools Tool Approach DevTools ClassLoader restart JRebel Bytecode rewriting HotSwap Limited JVM replacement DevTools doesn’t “reload classes” It replaces the ClassLoader that loaded them #Java #SpringBoot #JVM #ClassLoader #HotReload #BackendEngineering #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
Java Reflection: The "Backdoor" Frameworks Use to See Your Private Code Ever wondered how Spring magically injects dependencies into your private fields? Or how Hibernate reads your data without a single getter? Welcome to the Reflection API—the JVM’s ultimate "skeleton key." 🗝️ In standard Java, private means private. It’s the cornerstone of encapsulation. But frameworks operate on a different level. They don't just execute your code; they inspect its blueprint. 🛠️ The 3-Step "Heist" Introspection: The framework grabs the Class object—a mirror of your code. Discovery: It uses getDeclaredFields() to find every field, ignoring visibility rules. The Override: The magic command field.setAccessible(true) tells the JVM to look the other way, bypassing access checks entirely. ⚖️ The Trade-off While Reflection is a superpower for building flexible frameworks, it comes with a "tax": Performance: It’s significantly slower than direct calls because the JVM can’t optimize it as easily. Security: Modern Java (post-v9) has started tightening the screws with the Module System, requiring you to explicitly "open" packages to allow this level of deep inspection. Reflection turns your compiled code into a searchable database. It’s the reason we can use annotations like @Autowired or @Entity to handle the heavy lifting while we focus on business logic. What’s the trickiest use of Reflection you’ve encountered in a production codebase? 👇 #Java #JVM #BackendDevelopment #SoftwareEngineering #SpringFramework #SystemDesign #CodingTips #TheBytecodePhantom
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development