🔁 Follow-up to my previous post on preventing double booking using pessimistic locking. I’ve now implemented an optimistic locking version of the same Booking Service in a separate branch and tested it under concurrency. Key differences I observed: • ⚡ Higher throughput under low–moderate contention • 🔁 Failed updates detected via version checks (instead of blocking) • 🧠 Business logic must be retry-safe • ❗ Retries can amplify load under high contention This made the trade-offs very clear: • Pessimistic locking → safer under extreme contention, but blocks • Optimistic locking → faster, but needs careful retry + idempotency Both implementations are tested using Testcontainers + MySQL with concurrent booking attempts. 🔗 Optimistic locking branch: https://lnkd.in/gGtjjJSR #SystemDesign #BackendEngineering #Java #SpringBoot #DistributedSystems
Optimistic Locking vs Pessimistic Locking: Trade-Offs and Performance
More Relevant Posts
-
🚀 Day 37/100 - Spring Boot - Transactions (@Transactional) When working with databases, we often perform multiple operations that must either: ✔️ All succeed ❌ Or all fail This is where transaction's use come in - to ensure atomicity. ➡️ What is @Transactional? @Transactional tells Spring to execute a method within a database transaction. If something goes wrong, Spring automatically rolls back the changes. ➡️ Example: See attached image 👇 ➡️ What happens behind the scenes? 🔹 Spring opens a transaction 🔹 Executes all DB operations 🔹 If successful→commits 🔹 If exception occurs→rolls back This guarantees data consistency. ➡️ Why Transactions Matter? Without transactions: 🔹Partial updates can corrupt data 🔹Inconsistent state issues 🔹Hard to debug production problems Next post: https://lnkd.in/dsyjV2-e Previous post: https://lnkd.in/djmAw-fE #100Days #SpringBoot #Java #Transactions #BackendDevelopment #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
One line of code that saved our production database. We had a query returning 50,000 rows when we only needed 10. The API was timing out. Users were frustrated. The fix: Before: List<User> users = userRepository.findAll(); After: Pageable pageable = PageRequest.of(0, 10); Page<User> users = userRepository.findAll(pageable); Same query. 10 rows instead of 50,000. Response time went from 8 seconds to 200ms. Pagination is not optional. It is survival. What simple fix saved your production system? #Java #SpringBoot #Database #Performance #BackendDevelopment
To view or add a comment, sign in
-
🔐 How Interceptors Help Build Secure and Scalable APIs in Spring Boot Most backend applications need more than just controllers and services. They need: ✔ Authentication ✔ Authorization ✔ Validation ✔ Logging ✔ Monitoring Instead of scattering this logic everywhere, interceptors allow us to centralize it in one request pipeline. With a well-designed interceptor architecture, you can: ➡ Intercept requests before they reach controllers ➡ Plug in different authentication mechanisms (Basic, JWT, API Key) ➡ Enforce role-based access ➡ Validate requests (files, headers, size, format) ➡ Handle security errors consistently This approach keeps business logic clean and security modular. The diagram below shows a high-level view of how requests flow through interceptors, authentication layers, and controllers before generating a response. Understanding this pipeline helps you move from using frameworks to engineering systems. 💬 How are you handling authentication and validation in your APIs? #SpringBoot #BackendEngineering #APISecurity #SoftwareArchitecture #Java #CleanCode #SystemDesign #DevLearning
To view or add a comment, sign in
-
-
A simple change that made our API handle 3x more requests. We had a payment processing API that was slowing down under load. Every request was blocking a thread while waiting for the database and external payment gateway to respond. 50 concurrent users and the server was struggling. The fix was switching from Spring MVC to Spring WebFlux. Before: One thread per request. Thread sits idle waiting for response. After: Non-blocking. One thread handles multiple requests while waiting for IO. Same server. Same resources. Before: 200 requests per second After: 600 requests per second 40% reduction in response time under heavy load. Spring WebFlux is not always the answer. But when your bottleneck is IO and waiting, it changes everything. When did you switch from blocking to reactive and what difference did it make? #Java #SpringBoot #SpringWebFlux #Performance #BackendDevelopment
To view or add a comment, sign in
-
⚡ Why Transaction Boundaries Matter in Spring Boot Applications One thing that separates stable backend systems from fragile ones: Understanding transaction boundaries. In many Spring Boot projects, I’ve seen: ❌ @Transactional added everywhere without thinking ❌ Large service methods doing too many DB operations ❌ Unexpected rollbacks due to unchecked exceptions ❌ LazyInitializationExceptions because of wrong transaction scope What works better: ✅ Keep transactions small and focused ✅ Define them at the service layer (not controller) ✅ Understand propagation behavior ✅ Avoid mixing external API calls inside DB transactions A transaction is not just a database feature, it defines data consistency boundaries. 👉 Clean transaction design prevents hidden production bugs. #Java #SpringBoot #Transactions #BackendDevelopment #SoftwareArchitecture #CleanCode
To view or add a comment, sign in
-
Most systems don’t fail because of traffic. They fail because of poor design decisions. Example: Caching. When to use cache? High read, low write Data that can tolerate slight staleness When NOT to use cache? Real-time financial data Frequently changing records Simple decisions like this can reduce database load by 70–80%. System Design is less about tools, more about trade-offs. #SystemDesign #Java #Backend #Microservices
To view or add a comment, sign in
-
Here is how I debug slow APIs before touching the code. Most developers jump straight into the code when an API is slow. I check these things first: —> Is it the database? Turn on query logging. Look for queries taking more than 100ms. Most slow APIs are slow queries in disguise. —> Is it N+1? One API call triggering 100 database calls. Add JOIN FETCH or batch your queries. Instant fix. —> Is it missing indexes? Run EXPLAIN on your slow query. If you see sequential scan on a large table, add an index. —> Is it external service calls? API calling another API calling another API. Add timeouts. Add circuit breakers. Add async where possible. —> Is it serialization? Returning 50 fields when frontend needs 5. Use DTOs or projections. Stop sending the entire entity. —> Is it connection pool exhaustion? Database connections maxed out. Threads waiting. Check your pool size and connection timeout settings. —> Is it missing caching? Same data fetched 1000 times per minute. Add Redis or in-memory cache for static lookups. 90% of slow APIs fall into one of these categories. Fix the right problem first. Then optimize the code. What is your go-to first step when debugging a slow API? #Java #SpringBoot #Performance #Backend #SoftwareDevelopment
To view or add a comment, sign in
-
I once noticed a random latency spikes in one of our backend services. Locally everything worked fine. In lower environments too. But in production, response times would suddenly jump from 200ms to 3–4 seconds. After digging deeper, the issue wasn’t Spring Boot or the server size. It was database behavior under real traffic. The root cause: • A frequently used API was triggering an unindexed query • Under load, it caused full table scans • Connection pool threads started waiting • Latency cascaded across dependent services The fix wasn’t scaling the service. It was: • Adding proper indexing • Refactoring the query • Monitoring slow query logs • Tuning connection pool configuration Response time stabilized immediately. Sometimes performance problems aren’t architecture issues. They’re visibility and fundamentals issues. #PerformanceTuning #ScalableSystems #SoftwareEngineering #Tech #Developer #SpringBoot #Microservices #Java
To view or add a comment, sign in
-
Most Spring Boot bugs aren’t annotation problems. They’re flow problems. When you hit an API endpoint, do you actually know what happens next — or do you just hope it works? This is the real request journey in Spring Boot: Client → Controller → Service → Repository → Database → Response In this carousel, I break down: • how a request enters your application • where business logic should live • how data moves to and from the database • how the response is created Once this flow clicks, debugging stops feeling random. #SpringBoot #JavaDeveloper #BackendEngineering #RESTAPI #LearnJava #SpringFramework
To view or add a comment, sign in
-
When I started building my server in Express, I did the classic: ❌ try/catch in every controller ❌ Sending response, status code everywhere. I thought: “Nice! Errors handled!” 😎 But nope… not the best approach. 💡 The trick? Middleware. The best place to handle errors is middleware, not controllers. When something goes wrong 💥, we call next(err) ▶ next is basically Express saying: “Okay, something went wrong… skip everything else and handle it properly.” Perfect for operational errors (expected errors): ✔️ Invalid input. ✔️ Wrong route. ✔️ DB issues. ✔️ Timeouts. For programming errors (bugs): ❌ Unexpected ❌ Usually need fixing, not catching ✨ Better workflow now: ✅ Pass errors to next(err). ✅ Use global error middleware. ✅ Custom Error class. ✅ Async wrapper for controllers Result? 🧼 Clean controllers. 🎯 Single responsibility. 🛠 Easier debugging. ✨ Big takeaway: 🚨Controllers shouldn’t worry about how errors are handled. 💬 Hope this helps anyone learning error handling! ❤ #NodeJS #ExpressJS #BackendDev #ErrorHandling #LearningInPublic
To view or add a comment, sign in
-
More from this author
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