Ever wondered what really happens when a JSON request hits a Spring Boot application? Here’s a quick, simplified journey ➡️ 1. Incoming Request (JSON) A client sends a JSON payload over HTTP. This request lands on the embedded server (usually Tomcat). ➡️ 2. Tomcat Thread Handling Tomcat assigns a thread from its pool to handle the request — this ensures multiple users can be served concurrently. ➡️ 3. Filters (Pre-processing) Before reaching your application logic, the request passes through filters (e.g., logging, CORS, security checks). ➡️ 4. DispatcherServlet (The Traffic Controller) Spring’s DispatcherServlet takes over — it’s the central hub that routes requests to the right components. ➡️ 5. Authentication & Security If security is enabled, Spring Security intercepts the request, validates tokens/credentials, and decides access. ➡️ 6. Handler Mapping DispatcherServlet finds the correct controller method based on URL, HTTP method, and annotations. ➡️ 7. JSON → Java Object (Jackson Magic) The request body is converted into a Java object using Jackson (via HttpMessageConverters). ➡️ 8. Controller Execution Your controller method runs with the mapped object and business logic kicks in. ➡️ 9. Response Flow Back The response object is converted back to JSON and sent through the same chain (in reverse). 💡 In short: JSON → Tomcat Thread → Filters → DispatcherServlet → Security → Controller Mapping → Object Conversion → Business Logic → Response Clean, structured, and highly extensible — that’s the beauty of Spring Boot. #SpringBoot #Java #BackendDevelopment #SoftwareEngineering #WebDevelopment #KSAJobs #RiyadhJobs #OpenToWork
How Spring Boot Handles JSON Requests
More Relevant Posts
-
The Spring Boot annotation that is silently corrupting your database. If you are a Spring Boot developer, you probably use @Transactional every day. If something fails, the database rolls back. Simple, right? But what happens when you write code like this? @Service public class UserService { // The entry point called by the Controller public void registerUser(UserDTO dto) { // ... some validation logic ... saveUserAndSendEmail(dto); } @Transactional public void saveUserAndSendEmail(UserDTO dto) { userRepository.save(new User(dto.email())); emailService.sendWelcomeEmail(dto.email()); // What if this throws an exception? } } What you think happens: If the email service fails and throws an exception, @Transactional catches it, rolls back the database insert, and the user is not saved. What ACTUALLY happens: The database commits the user anyway. Your system now has a user who never got their welcome email, and your database is in an inconsistent state. Why did it fail? The "Proxy Bypass" Trap. Spring’s @Transactional doesn't work by magic; it works by creating an AOP Proxy around your class. When an outside class (like your Controller) calls your Service, it hits the Proxy first, which opens the database transaction. BUT... if you call a method from within the same class (like registerUser calling saveUserAndSendEmail), you are using the internal this reference. You completely bypassed the Spring Proxy. The transaction never started. The rollback will never happen. The Senior Fixes: 1. The Architecture Fix: Move the @Transactional logic to a separate UserRegistrationService. Calling an external class forces you to go through the proxy. 2. The Simple Fix: Put @Transactional on the entry-point method (registerUser) instead of the internal helper method. Stop assuming annotations are magic. If you don't understand how proxies work under the hood, your data is at risk! Have you ever spent hours debugging a @Transactional rollback that just wouldn't trigger? 👇 #Java #SpringBoot #Hibernate #BackendDevelopment #Microservices #SoftwareEngineering #CleanCode #TechTips #LogicLedaMagic
To view or add a comment, sign in
-
Over the past few days, I worked on designing and documenting a complete Spring Security implementation using JWT (JSON Web Tokens) for stateless authentication. This wasn’t just a demo — it’s structured like a real-world, scalable backend system. 💡 Key Highlights: ✔️ Stateless authentication using JWT ✔️ Secure password handling with BCrypt (strength 12) ✔️ Role-based authorization (ROLE_USER / ROLE_ADMIN) ✔️ Custom security filter with OncePerRequestFilter ✔️ Clean layered architecture (Controller → Service → Repository) ✔️ Database versioning using Flyway ✔️ Lightweight data access using JdbcTemplate (no JPA) 🔐 Security Flow Simplified: Every request passes through a custom JWT filter → token validation → user authentication → role-based authorization via Spring Security. ⚙️ Tech Stack: Spring Boot 4 Spring Security 6+ JWT (JJWT) Flyway Migration MySQL Lombok JdbcTemplate 📌 What I Focused On: Writing clean, maintainable security configuration Avoiding common pitfalls (CSRF misuse, hardcoded secrets, session state) Designing for real-world production readiness 📊 Why this matters: In modern microservices architecture, stateless security with JWT is critical for scalability, performance, and decoupled services. 💬 I’m currently exploring deeper into Spring ecosystem, system design, and cloud-native architectures. If you're working on similar implementations or have insights, let’s connect and discuss! #SpringBoot #SpringSecurity #JWT #Java #BackendDevelopment #Microservices #SystemDesign #SoftwareEngineering #TechLeadership #Flyway #Security #HappyLearning
To view or add a comment, sign in
-
Most developers think Spring handles 500 requests “all at once.” It doesn’t. Here’s what actually happens: Spring Boot (via embedded Tomcat in Spring Boot) uses a thread pool to handle incoming requests. Each request follows this path: → Request arrives at Tomcat → A free thread is assigned → DispatcherServlet routes it to your @RestController → Controller → Service → Database → Response is returned → Thread goes back to the pool That’s it. No magic. ━━━━━━━━━━━━━━━━━━━━ What happens when all threads are busy? → New requests are placed in a queue → If the queue is full, requests may be rejected (e.g., 503 errors depending on configuration) ━━━━━━━━━━━━━━━━━━━━ The real bottleneck isn’t traffic, it’s blocked threads. Consider this: A slow database call takes 3 seconds × 200 threads = Your system can stall under moderate load This is why backend engineers focus on: Thread pool tuning Reducing blocking operations Asynchronous processing (@Async) Efficient database access (connection pooling) Non-blocking architectures (Spring WebFlux) Key takeaway: Performance is not about handling more requests. It’s about how efficiently your threads are utilized. #Java #SpringBoot #Concurrency #BackendDevelopment #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
Your Spring Boot app creates thousands of objects per request. You just never noticed. A simple GET /api/users/123 triggers all of this behind the scenes: → Tomcat creates HttpServletRequest + HttpServletResponse objects → Spring Security creates SecurityContext for auth check → Every servlet filter wraps the request in a new decorator object → Hibernate creates proxy objects for every lazy-loaded entity → Dirty checking — Hibernate snapshots every field of every entity to compare later → Jackson creates intermediate nodes during JSON serialization → Every String concatenation in logs creates a new String object → AOP proxy for @Transactional wraps your service in another object One request. Thousands of framework objects. You wrote 10 lines. The framework created the rest. At low traffic, you never notice. GC handles it quietly. At 1,000 RPS → millions of short-lived objects per second. Young gen fills fast. GC runs every few milliseconds. p99 latency spikes. Throughput drops 10-20%. No errors. No exceptions. Just slower. How to reduce it: → Return DTOs, not entities — avoids proxy creation + dirty checking → @Transactional(readOnly=true) for reads — skips dirty checking entirely → log.info("User {}", id) not log.info("User " + id) — avoids String garbage → Primitives over boxed types — int not Integer → Tune young gen: -XX:NewRatio=2 The fastest code isn't the code that runs fastest. It's the code that creates the least garbage. #springboot
To view or add a comment, sign in
-
I thought our Spring Boot API was fast… until we hit 1,000 users Everything worked perfectly in my local environment. But in production, our dashboard became painfully slow. The logs told the real story: Hundreds of SQL queries… for a single request. I had accidentally introduced the infamous N+1 Query Problem. 🔴 The Mistake I was fetching Users and their Orders using "findAll()". Since the relationship was "FetchType.LAZY" (default), Hibernate did this: • 1 query → fetch all Users • N queries → fetch Orders for each User 👉 With 1,000 users = 1,001 database calls for one page load 😬 🟢 The Fix Used "JOIN FETCH" in a custom query: @Query("SELECT u FROM User u JOIN FETCH u.orders") List<User> findAllWithOrders(); This forces Hibernate to fetch everything in a single SQL join. ⚡ The Result • Database calls: 1,001 → 1 • Response time: 5s → <200ms • Server CPU: Stable again 📌 The Lesson Performance issues often hide in “innocent” code. Don’t blindly trust default JPA behavior. Always monitor SQL logs during development — your future self will thank you. Have you ever been bitten by the N+1 problem? What’s your go-to solution — "JOIN FETCH" or "EntityGraph"? #Java #SpringBoot #Hibernate #BackendDevelopment #Performance #DatabaseOptimization #CleanCode
To view or add a comment, sign in
-
50ms → 12 seconds. Zero deploys. Zero code changes. That's what happens to a Java backend API under real load. Just 7 Spring Boot defaults your team never configured: 1. 𝗖𝗼𝗻𝗻𝗲𝗰𝘁𝗶𝗼𝗻 𝗣𝗼𝗼𝗹 ↳ HikariCP ships with 10 connections. Your app runs 200 Tomcat threads. 200 threads fighting for 10 slots. CPU at 5%. Memory fine. App frozen. Nothing in the logs tells you why. 2. 𝗡+𝟭 𝗤𝘂𝗲𝗿𝗶𝗲𝘀 ↳ One JPA call loads 1 user just fine. Same call at 10K users fires 10,000 queries. Your DBA pages you at 2 AM. 3. 𝗡𝗼 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 ↳ Every GET request hits the database. At 100 users nobody notices. At 10K your DB CPU pins at 98% and every request queues behind the last. 4. 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗖𝗮𝗹𝗹𝘀 ↳ One slow downstream microservice blocks a thread. Multiply by 10K users. Tomcat pool exhausted. App stops responding. Health check passes. Load balancer keeps sending traffic. 5. 𝗦𝗲𝘀𝘀𝗶𝗼𝗻 𝗦𝘁𝗼𝗿𝗮𝗴𝗲 ↳ In-memory sessions on one server. Add a second for load balancing. Users start getting logged out mid-session. Support tickets spike. Nobody connects the dots. 6. 𝗡𝗼 𝗥𝗮𝘁𝗲 𝗟𝗶𝗺𝗶𝘁𝗶𝗻𝗴 ↳ No API gateway. No throttling. One bot sends 5K requests/sec. Your entire service goes down before anyone gets paged. 7. 𝗩𝗲𝗿𝗯𝗼𝘀𝗲 𝗟𝗼𝗴𝗴𝗶𝗻𝗴 ↳ DEBUG level left on in production. Disk fills in hours. App crashes. Not from traffic. From your own logs. ⚠️ Most scalable SaaS backends running Spring Boot have at least 3 of these right now. All 7 pass unit tests. All 7 work in staging. 𝗡𝗼𝗻𝗲 𝘀𝘂𝗿𝘃𝗶𝘃𝗲 𝟭𝟬,𝟬𝟬𝟬 𝗿𝗲𝗮𝗹 𝘂𝘀𝗲𝗿𝘀. 💾 Save this before your next deploy. ♻️ Repost if your backend team hasn't checked these. 👤 Follow Gopal Sabhadiya for Java backend scaling. Which one already broke in YOUR system? 👇
To view or add a comment, sign in
-
🚀 New Project: Secure Authentication with Spring Boot I recently built a Login & Registration system and wanted to share the logic behind the scenes! This was a great exercise in handling RESTful APIs and database management. 🧠 The Logic: Registration: Captures user data via POST, validates inputs, and persists it to a MySQL database using Spring Data JPA. Login: Fetches the user by ID/Username and validates credentials. If they match, a success response is sent; otherwise, an error is handled. API Verification: Used Postman to test every edge case—ensuring correct JSON responses and HTTP status codes (200 OK, 401 Unauthorized, etc.). 🛠️ Tech Stack: Java 21 & Spring Boot 3.3.5 MySQL for reliable data storage OpenAPI for easy API exploration Check out the screen recording below to see the UI and "Login Successful" flow! 📽️ 📂 View on GitHub: https://lnkd.in/dbCiX_T4 #Java #SpringBoot #BackendDevelopment #Postman #MySQL #CSStudent #CodingLogic
To view or add a comment, sign in
-
🚀 3-Layer Architecture in Spring Boot (Industry Standard) Every professional Spring Boot application follows a 3-layer architecture to keep code clean, scalable, and production-ready. 🔄 Flow: Client (Browser/Postman) → Controller → Service → Repository → Database 🔷 Controller Layer (@RestController) 👉 Handles HTTP requests & responses 👉 Defines API endpoints 🔷 Service Layer (@Service) 👉 Contains business logic 👉 Decides what actions to perform 🔷 Repository Layer (@Repository / JpaRepository) 👉 Communicates with database 👉 Performs CRUD operations using JPA/Hibernate 🗄️ Database (MySQL) 👉 Stores and manages application data 💡 Why it matters? ✅ Clean code structure ✅ Easy maintenance & debugging ✅ Scalable for real-world apps ✅ Industry best practice 📌 Example Flow: User sends request → Controller receives → Service processes → Repository fetches data → Response returned 🔥 In short: Controller = Entry 🚪 Service = Brain 🧠 Repository = Data 💾 #SpringBoot #Java #Backend #SoftwareArchitecture #SystemDesign #JPA #Hibernate #Developers #Coding
To view or add a comment, sign in
-
-
Hidden N+1 in Spring Boot endpoint This endpoint runs 78 SQL queries… for a single request. And no one noticed. During a performance review, I analyzed a simple API: @GetMapping("/owners") public List<OwnerDto> getOwners() { return ownerRepository.findAll().stream() .map(owner -> new OwnerDto( owner.getId(), owner.getLastName(), owner.getPets().size() // ⚠️ hidden query )) .toList(); } Looks clean. Looks harmless. 🚨 What actually happens 1 query → fetch owners +1 query per owner → fetch pets 👉 With 77 owners: 1 + 77 = 78 SQL queries 💥 Real impact (measured) up to 1.2s per request ~29s cumulative DB time massive DB load under traffic ⚠️ Why this is hard to spot code looks clean no errors works fine in dev explodes only with real data ✅ Fix @EntityGraph(attributePaths = "pets") List<Owner> findAll(); 👉 Single query instead of dozens. 🧠 Takeaway Most performance issues are not in your code. They are in your data access patterns. 🔍 Bonus I built a small tool that detects this automatically: 👉 https://www.joptimize.io/ It highlights: N+1 queries slow endpoints hidden database overhead Are you sure your endpoints are not doing 10x more queries than expected? #JavaDev #SpringBoot #Hibernate #JavaPerformance #Backend #SoftwareEngineering
To view or add a comment, sign in
-
N+1 Query Problem (Hibernate / JPA) Your Spring Boot app is fast… until it hits the database. Then suddenly: 👉 1 query becomes 101 👉 and your API dies under load I saw this in a production audit last week. // ❌ Looks harmless List<User> users = userRepository.findAll(); for (User user : users) { System.out.println(user.getOrders().size()); } 🚨 What actually happens: • 1 query to fetch users • +1 query PER user to fetch orders 👉 This is called the N+1 problem 💥 Real production impact: • DB overload • Massive latency increase • Works in dev… crashes in prod ⚠️ Important nuance (don’t get roasted in comments 😄) This happens when: 👉 @OneToMany(fetch = LAZY) (default) If it's EAGER, behavior changes (but creates other problems) ✅ Fix: // ✔️ Use fetch join @Query("SELECT u FROM User u JOIN FETCH u.orders") List<User> findAllWithOrders(); OR // ✔️ Use EntityGraph @EntityGraph(attributePaths = "orders") List<User> findAll(); 🧠 Takeaway: If you don’t control your queries… your database will control you. Are you sure your app isn’t doing 100 hidden queries right now? #JavaDev #SpringBoot #Hibernate #JavaPerformance #Backend #SoftwareEngineering
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