Saga Pattern and Two-Phase Commit in Java Saga and Two-Phase Commit (2PC) are approaches to managing distributed transactions in microservices, where operations span multiple databases or services, as in Java and Spring. They address data consistency issues when single-database ACID transactions fall short. Saga suits high availability, while 2PC ensures strict atomicity. How the Saga Pattern Works✅ Saga breaks a long transaction into local steps, each with a compensating action for rollback. • Orchestration: A central coordinator manages steps (e.g., order → payment → warehouse). On failure, compensations run in reverse. • Choreography: Services communicate via events (Kafka or RabbitMQ), without a coordinator—each step triggers the next. In Java, implement via Spring Boot with Axon Framework or Eventuate Tram: use @SagaStart and @SagaEnd annotations for steps. Example: reduce warehouse stock + deduct payment; if payment fails, compensate by returning goods. How Two-Phase Commit (2PC) Works✅ 2PC is a blocking protocol with a coordinator and two phases: prepare and commit. • Phase 1 (Prepare): Coordinator asks participants (DBs, services) if ready; they reserve resources and vote YES/NO. • Phase 2 (Commit/Rollback): All YES → commit; else rollback. Locks resources until done. In Java/Spring, use JTA (Java Transaction API) with Atomikos or Narayana: @Transactional with propagation=REQUIRED and xa-data-source for multiple DBs. Example: two DBs (warehouse and bank) sync via UserTransaction
Maxim Konstantinov’s Post
More Relevant Posts
-
Java records are powerful. But they are not a replacement for every POJO. That is where many teams get the migration decision wrong. A record is best when your type is mainly a transparent carrier for a fixed set of values. Java gives you the constructor, accessors, equals(), hashCode(), and toString() automatically, which makes records great for DTOs, request/response models, and small value objects. But records also come with important limits. A record is shallowly immutable, its components are fixed in the header, it cannot extend another class because it already extends java.lang.Record, and you cannot add extra instance fields outside the declared components. You can still add validation in a canonical or compact constructor, but records are a poor fit when the model needs mutable state, framework-style setters, or inheritance-heavy design. So the real question is not: “Should we convert all POJOs to records?” The better question is: “Which POJOs are actually just data carriers?” That is where records shine. A practical rule: use records for immutable data transfer shapes, keep normal classes for JPA entities, mutable domain objects, lifecycle-heavy models, and cases where behavior and state evolve over time. Also, one important clarification: this is not really a “Java 25 only” story. Records became a permanent Java feature in Java 16, and Java 25 documents them as part of the standard language model. So no, the answer is not “change every POJO to record.” Change only the POJOs that truly represent fixed data. Where do you draw the line in your codebase: DTOs only, or value objects too? #Java #Java25 #JavaRecords #SoftwareEngineering #BackendDevelopment #CleanCode #JavaDeveloper #Programming #SystemDesign #TechLeadership
To view or add a comment, sign in
-
-
Develop with Java 17: Can a Java Record be used as a JPA Entity? 🤔 With the introduction of Records in Java, many developers wonder whether they can directly replace traditional entities in ORM frameworks. The short answer: No. A Java Record cannot be used as a JPA Entity. Here’s why: 🔹 Immutability Records are immutable by design. All fields are final, but JPA entities typically need mutable fields so the persistence provider can update them during the entity lifecycle. 🔹 No Default Constructor JPA requires a no-argument constructor so the ORM framework can instantiate entities via reflection. Records only provide a canonical constructor. 🔹 Final Classes Records are implicitly final, but frameworks like Hibernate rely on creating proxy subclasses for features such as lazy loading. So where do Records shine? ✅ DTOs and Projection Models Records are perfect for returning lightweight read models from queries. Example: public record UserDTO(Long id, String name) {} While using with repository: @Query("SELECT new com.example.UserDTO(u.id, u.name) FROM User u") List<UserDTO> findUsers(); This approach gives: ✔ Immutable data structures ✔ Less boilerplate ✔ Cleaner API responses 💡 Best practice: Use traditional classes for entities and Records for DTOs or projections. Java keeps evolving, and understanding where to apply each feature makes a big difference in writing clean and maintainable systems. #Java #Java17 #SpringBoot #Hibernate #JPA #SoftwareArchitecture #BackendDevelopment Credit:ChatGPT
To view or add a comment, sign in
-
A simple Data Structures concept that appears frequently in backend systems: HashMap collisions. Java’s HashMap provides average O(1) time for get() and put() operations. But this performance depends on how well keys are distributed across buckets. When two different keys produce the same hash, a collision occurs. Before Java 8: collisions were stored as linked lists. Worst-case lookup time could degrade to O(n). Since Java 8: when collisions in a bucket exceed a threshold, the structure converts to a balanced tree. This improves worst-case lookup to O(log n). Why this matters in real systems: Poorly designed hash keys or uneven key distribution can still create hot buckets and reduce performance. Even with high-level frameworks, understanding the underlying data structures helps explain unexpected latency in production systems.
To view or add a comment, sign in
-
🔴 Q1. What is JAVA and features of java? 🟢 Ans : Java is an high level , class based object oriented programming language that we used to developed java based application. Features: ➡️ 1. Object oriented - Follows OOPS concept ➡️2. Platform dependent - run on any any operation system without modification ➡️3. Simple language - Easy to learn in compared other languages ➡️4. Secure - No direct pointer access, Byte-code verification, Security manager control access ➡️5. Robust - String memory management, Exception handling mechanism, Compile & Runtime error checking ➡️6. Multi-tread - Multiple task to run simultaneously, Better CPU utilization, Faster application performance ➡️7. Portable - Byte-code can run on any platform, Same .class file works across platforms ➡️8. High performance - Using JIT converting byte-code into native machine code at runtime 🔴Q2. Difference between JDK,JVM,JRE 🟢Ans: ⭐ A] JDK : ➡️1. Java development kit ➡️2. JDK contains development tools and JRE ➡️3. JDK physically exists ➡️4. JDK is bundle of software used to develop java based application ➡️5. JDK is platform dependent ⭐B] JVM : ➡️1. Java virtual machine ➡️2. JVM providing environment for execution it. ➡️3. JVM physically not exists ➡️4. JVM works the java byte-code can be executed ➡️5. JVM is highly platform dependent ⭐C] JRE : ➡️1. Java Runtime environment ➡️2. JRE contains the set of libraries & other files ➡️3. JRE is implementation of JVM & Physically exist ➡️4. JRE works is provide runtime environment to user. ➡️5. JRE is also platform dependent
To view or add a comment, sign in
-
-
Suppressed Exceptions — The Half of Failure Most Systems Ignore Try-with-resources is not syntactic sugar. Treating it as such is a real production risk. Java 7 is often remembered as “automatic resource closing.” That explanation is convenient. It also misses the point. The real change in Java 7 was not about closing resources. It was about fixing an exception model that could only represent one failure, even when several occurred. Before Java 7, a common production sequence looked like this: - business logic fails - cleanup fails in a finally block - the cleanup failure overwrites the original exception - The system crashes — and the root cause quietly disappears. Java 7 introduced suppressed exceptions to address this exact problem: secondary failures are no longer allowed to replace the primary one. Try-with-resources is built on top of that semantic shift. It is not sugar. It is a consequence. I often use a medical metaphor. A production monolith is rarely sick in just one way. It is a multi-pathological patient. Ignoring suppressed exceptions is like treating the visible injury while leaving other conditions undiagnosed. The worst-case scenario is not the initial incident. It’s the fix — followed immediately by another crash after redeployment, caused by a failure that was already there, but never observed. I’ve published a longer version (see in the comments) that goes deeper into the JVM mechanics, along with a minimal Java example that makes this behavior explicit. No frameworks. No abstractions. Just real runtime behavior. The problem is not that the runtime hides information. It’s that most systems never look for it. Most systems don’t notice what they suppress.
To view or add a comment, sign in
-
The "Before & After" of Spring Framework: From Boilerplate to Automation 🚀 Before the Spring Framework, Java developers were stuck writing massive amounts of manual "infrastructure" code for every project. The "Old Way" (Manual Management): In the pre-Spring era, we had to: - Manually create objects using the "new" keyword every time a dependency was needed. - Manually manage the lifecycle (creation, initialization, and destruction) of every single object. - Handle Dependency Injection manually, which led to tightly coupled code that was a nightmare to test and maintain. The "Spring Way" (Inversion of Control): Spring introduced the IOC (Inversion of Control) Container. Instead of us manually managing objects, we give control to SPRING to instantiate, configure, and manage the entire lifecycle of our objects (Beans). How does Spring know which classes to manage? Spring follows a specific "blueprint" provided by the developer. There are two primary ways Spring identifies which classes should become Beans: 1️⃣ Stereotype Annotations (Component Scanning) Spring scans your project for classes marked with specific markers: - @Component: The generic marker for any Spring-managed component. - @Service: Specifically for business logic. - @Repository: For the data access layer. - @Controller / @RestController: For handling web requests. 2️⃣ Configuration Classes (Explicit Definition) Sometimes you need more control, especially when using third-party libraries. In this case, we use: - @Configuration: Marks a class as a source of bean definitions. - @Bean: Placed on a method; Spring executes this and registers the returned object as a Bean. The Result? Cleaner code, decoupled architectures, and more time for developers to focus on business logic instead of infrastructure. #SpringBoot #Java #SoftwareEngineering #BackendDevelopment #SpringFramework #CleanCode #ProgrammingTips #IOC #SoftwareArchitecture
To view or add a comment, sign in
-
-
Interesting article by Jose Antonio López Galdeano with a useful sample AGENTS.md to be used in Java projects. https://lnkd.in/d6Qwj3Jz #Java #Spring #SpringBoot #LLM #AI #AGENTS #Intellij
To view or add a comment, sign in
-
🚀 The Invisible Wall in Java Memory - Why Your Code Crashes Even With 32GB RAM Ever encountered this? Exception in thread "main" java.lang.StackOverflowError The server has 32GB RAM. The heap is barely touched. And yet - crash. What’s actually happening Java memory isn’t one big pool. Every thread gets its own stack - typically ~1MB by default. That stack holds: • Method frames • Local primitives • Object references It’s fast. It’s limited. And it’s completely separate from the heap. Deep recursion burns through that 1MB quickly. It doesn’t matter how much heap you have. 𝗦𝘁𝗮𝗰𝗸𝗢𝘃𝗲𝗿𝗳𝗹𝗼𝘄𝗘𝗿𝗿𝗼𝗿 ≠ 𝗢𝘂𝘁𝗢𝗳𝗠𝗲𝗺𝗼𝗿𝘆𝗘𝗿𝗿𝗼𝗿 One means your thread stack is exhausted The other means your heap is exhausted Confusing them costs hours in production debugging. JVM Heap tip • Always set -𝗫𝗺𝘀 and -𝗫𝗺𝘅 explicitly in production • Never rely on JVM defaults - it guesses, and guessing is expensive Common misconception When StackOverflowError hits, the first instinct is: 👉 “Increase the RAM.” Wrong lever entirely. • Stack isn’t heap • You can’t throw hardware at it • Recursion works… until it doesn’t • In production, “until it doesn’t” comes faster than expected The right mental model ✔️ Prefer iteration for deep recursion ✔️ -𝗫𝘀𝘀 controls thread stack size, but tune it only as a last resort ✔️ Set -𝗫𝗺𝘀 and -𝗫𝗺𝘅 explicitly - don’t trust JVM defaults ✔️ Remember: every thread has its own stack ✔️ Treat StackOverflowError as a design signal, not a runtime surprise Memory management isn’t just a C++ concern- every Java engineer should own it too.
To view or add a comment, sign in
-
-
#Spring #Container 👉 Spring Container is the core part of Spring Framework that creates, manages, and controls objects (Beans). ➡️ Simple meaning: Spring Container manages all objects of the application. 📌 Key Points • Creates Beans (objects) 🧩 • Manages Dependency Injection (DI) 🔗 • Controls Bean lifecycle 🔄 • Reads configuration (XML / Java / Annotation) ⚙️ • Makes application loosely coupled 🔑 Types of Spring Container 1️⃣ BeanFactory • Basic container • Lightweight • Used for simple applications 2️⃣ ApplicationContext ⭐ • Advanced container • Most commonly used • Supports AOP, events, internationalization Example: ApplicationContext context = new ClassPathXmlApplicationContext("config.xml"); 🎯 Real Time Example (HRMS Project) Classes: EmployeeService EmployeeRepository DataSource 👉 Spring Container creates these objects and connects them automatically using DI. ⭐ One Line 👉 Spring Container is responsible for creating, configuring, and managing Spring beans in the application.
To view or add a comment, sign in
-
Disappear till APRIL 2026 and.. Clear all Java Backend Rounds!! Here is HOW can you do in 6 steps 𝗦𝘁𝗲𝗽 𝟭: 𝗖𝗼𝗿𝗲 𝗝𝗮𝘃𝗮 - Data Types - Loops & Conditionals - OOP - Exception Handling - Collections Framework (List, Set, Map, Queue) - Java 8+ Features (Streams, Lambda, Functional Interfaces) 𝗦𝘁𝗲𝗽 𝟮: 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗝𝗮𝘃𝗮 - Multithreading & Concurrency - JVM Internals & Garbage Collection - Design Patterns (Singleton, Factory, Builder, Observer) - Annotations & Reflection - File Handling & Serialization 𝗦𝘁𝗲𝗽 𝟯: 𝗦𝗽𝗿𝗶𝗻𝗴 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 - Spring Core & IoC - Spring Boot (Auto Configuration, Starters) - REST API Development - Spring Data JPA & Hibernate - Security (JWT, OAuth2) 𝗦𝘁𝗲𝗽 𝟰: 𝗗𝗮𝘁𝗮𝗯𝗮𝘀𝗲 - SQL (DDL, DML, Joins, Indexes, Transactions) - Query Optimization - NoSQL Basics (MongoDB, Redis) 𝗦𝘁𝗲𝗽 𝟱: 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 & 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀 - JUnit & Mockito - Integration Testing - Logging (SLF4J, Logback) - Code Quality (SonarQube, Clean Code Principles) 𝗦𝘁𝗲𝗽 𝟲: 𝗗𝗲𝘃𝗢𝗽𝘀 & 𝗖𝗹𝗼𝘂𝗱 𝗘𝘀𝘀𝗲𝗻𝘁𝗶𝗮𝗹𝘀 - Git & GitHub - CI/CD Basics (Jenkins, GitHub Actions) - Docker & Kubernetes Fundamentals - AWS / Azure / GCP Basics JAVA Backend can be tough to crack, but having the right resources makes all the difference. Came across this well-structured, in-depth guide definitely worth a read. 𝗖𝗵𝗲𝗰𝗸 𝗶𝘁 𝗼𝘂𝘁 𝗵𝗲𝗿𝗲: https://lnkd.in/g5rkp6em
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