Interview Preparation
Version 0.1
Document Overview
This document is intended to specify the interview processes and actual scenarios asked at the time of interview.
Purpose
The purpose of this document is to describe what
needs to learn the concepts will describe and learn prepare for java interview.
The information contained in this document
provides the detailed functional analysis for the interview process.
Version Log
|
Date |
Author |
Version |
Change
Description |
|
04/17/2025 |
Srikanth Mamillapalli |
0.1 |
Initial Draft |
Table of Contents
1. Core
Java Important Concepts for Interview
1.1 java different version features
1.6 Aggregate (Reduction) Functions in Java 8 Streams
1.9 Functional Interfaces (SAM)
1.10 Collection Internal Data Structure
1.13.1
Comparator Java 8 Enhancements
1.13 What is Cohesion and Coupling
1.14 JVM AND Core Java Very Important INTERVIEW_QUESTIONS
1.14.2 JVM Memory Areas Recap:
1.14.3 JVM Memory Diagram (Java 8+)
1.14.4 Garbage Collection algorithms in Java
1.14.5 What are the best practices for designing immutable
classes?
1.14.6 How does synchronized, ReentrantLock, ExecutorService
work?
1.14.7 How is HashMap works internally/implemented
1.14.8 How is ConcurrentHashMap implemented?
1.14.9 What is the difference between HashMap and
ConcurrentHashMap?
1.14.11 ReentrantLock
implements Lock
1.14.12 How
would you implement a thread-safe LRU cache?
1.14.15 Explain
memory leaks in Java. How do you detect and fix them?
1.14.16 Bestways
to use Concurrency in Java:
2. Micro
Service Design Patterns
2.21 Common GoF Design Patterns in Spring
Boot/Microservices
5. SAGA
Sagas Are Global Atomic Transactions
5.1 Choreography (event-driven)
5.2 Orchestration (central controller)
8.1 Master Node (Control Plane)
How does Spring Security work internally?
What is the difference between Authentication and
Authorization?
What is a Security Filter Chain?
What is JWT and how does it work?
How is JWT used in Spring Security?
How do you secure a REST API using Spring Security and
JWT?
What is OncePerRequestFilter and why is it used in
JWT?
Where do you validate JWT in Spring Security?
How do you create a custom authentication entry point?
How do you handle token expiration and refresh?
Is JWT secure? What are the common risks?
How do you manage user roles and permissions in JWT?
What is @PreAuthorize vs @Secured?
What is the use of SecurityContextHolder?
How do you handle CSRF in a JWT-based application?
How to expose authentication and user details in
controllers?
OAuth 2.0 Auth Flow (e.g., Google Login)
OAuth 1.0 vs OAuth 2.0 – Key Differences
11.4 There are different types of ApplicationContext
11.5.1
Dependency Injection (DI):
11.5.2 Aspect-Oriented Programming (AOP):
ü Aspect: A module that
encapsulates cross-cutting logic.
ü Advice: The action taken
at a join point (@Before, @After, etc.).
ü Join
Point:
A point during execution (e.g., method call).
ü Pointcut: A predicate that
matches join points.
11.5.4 Important Modules in Spring
11.5.6 How Spring Works (Internally)?
11.5.8 Ways to Configure Spring
12.1 Core Spring Boot Annotations
12.2 How does Spring Boot auto-configuration work?
12.5 @Qualifier Common Scenarios for @Qualifier
12.7 Persistence (Spring Data JPA)
12.10 Test Annotations (Spring Boot Test)
12.12 SpringBoot Application invocation:
12.13 Different approaches of designing class having
dependency
How to create a singleton beans in SpringBoot
12.14 how to create Mutable state in Springboot
12.15 Handle Exception in SpringBoot
12.16 Different actuator in SpringBoot
12.18 Metrics in Spring Boot (Micrometer)
12.19 Enabling Prometheus Exporter
12.21 Spring Boot Core Starters
12.22 Spring Boot realistic,
end-to-end flow of a Microservices
system
12.22.1
end-to-end flow of a Microservices system
12.21.2 High-Level
Architecture
12.23 Spring Boot-level transactions
12.24 Global Exception Handler
12.25 Explain how you designed a scalable
microservices architecture in Spring Boot.
12.26 Microservice Design Principles
12.31 What is the role of Spring Cloud Config? How do
you manage configurations in production?
12.32 How do you secure microservices (OAuth2, JWT,
Spring Security)?
12.32.1 Authentication
and Authorization in Microservices
12.32.2 Core
Security Components
12.32.5 What’s
your approach to versioning REST APIs?
12.32.6 Why
API Versioning Matters
12.32.7 Best
Practices for API Versioning
12.32.8 What’s your approach to ensuring high
availability and fault tolerance?
Microservices Architecture Design
How to Run Spring Boot Actuator on a Different Port
To override or customize the /health endpoint
How do you design a microservices system using Spring
Boot?
What is a Reactive Programming?
where your Spring Boot app needs to process a large
file efficiently
How to increase the performance or tune the queries
13.1 What is index and what are the types of index
13.2 What is the cursor and refcursor in pl/sql
13.4 IN,OUT,IN_OUT parameters in database stored
procedure
13.6 execute a stored procedure from
java/springboot/jpa
13.8 CTE common table expressions
13.10 JPA Repository and CURD Repository
13.12.1 What
is @Transactional in Spring?
13.12.2 What
are the default properties of @Transactional?
13.12.3 What
happens if an exception is caught and not rethrown in a @Transactional method?
13.12.4 What
happens when one @Transactional method calls another in the same class?
13.12.5 What
is the role of readOnly=true?
13.12.6 How
is transaction managed in Spring Boot JPA?
13.12.7 How
does @Transactional work internally?
13.12.9 What
is transaction propagation?
|
Java8 |
Java11 |
Java21 |
|
Lambda Expressions |
Local-Variable Syntax for |
Record Patterns |
|
Functional Interfaces |
New String Methods |
Pattern Matching for switch |
|
Method References |
New File Methods |
Virtual Threads |
|
Default Methods |
HTTP Client (Standardized) |
Sequenced Collections |
|
Static Methods in Interfaces |
Collection Enhancements |
String Templates |
|
Stream API |
Launch Single-File Programs |
Incubator Features |
|
Date and Time API |
|
Scoped Values |
|
Optional Class |
|
Unnamed Patterns and Variables |
|
Nashorn JavaScript Engine |
|
Unnamed Classes |
|
Parallel Streams |
|
Instance Main Methods |
|
CompletableFuture |
|
Foreign Function & Memory API |
|
Collectors Utility |
|
Structured Concurrency |
|
Streams |
Functional Interfaces |
|
|
Lambda Expressions |
intermediate operations |
Function<T, R> |
|
Functional Interfaces |
Filter(Predicate) |
BiFunction<T, U, R> |
|
Method References |
Map(Function) |
Consumer<T> |
|
Default Methods in Interfaces |
flatMap Function<T, Stream<R>> |
BiConsumer<T, U> |
|
Static Methods in Interfaces |
Distinct uses Object.equals() and hashCode() |
Supplier<T> |
|
Stream API |
sorted() Comparator<T> |
Predicate<T> |
|
Date and Time API (java.time) |
limit(n) |
BiPredicate<T, U> |
|
Optional Class |
skip(n) |
UnaryOperator<T> |
|
Nashorn JavaScript Engine |
Peek Consumer<T> |
BinaryOperator<T> |
|
Parallel Streams |
Terminal Operations |
Map new Features |
|
CompletableFuture |
collect(Collectors) |
forEach |
|
Collectors Utility |
forEach(Consumer) |
getOrDefault |
|
|
count() |
putIfAbsent |
|
|
anyMatch() Predicate<T> |
computeIfAbsent |
|
|
allMatch() Predicate<T> |
computeIfPresent |
|
|
noneMatch()Predicate<T> |
compute |
|
|
findFirst() Retrieves optional result |
merge |
|
|
findAny() Retrieves optional result |
Replace |
|
|
reduce() BinaryOperator<T> |
remove |
|
Category |
Feature |
Description |
|
New Language Feature |
var in lambda parameters |
Allows use of var in lambda expressions. |
|
Standard API Changes |
String methods enhancements |
New methods like isBlank(), lines(), strip(),
repeat(). |
|
Files.readString() and Files.writeString() |
Simplifies reading/writing files as strings. |
|
|
Optional.isEmpty() |
Opposite of isPresent(), adds clarity. |
|
|
Garbage Collection |
Z Garbage Collector (ZGC) |
Low-latency GC; scalable and unnoticeable
pause times. |
|
Epsilon GC |
A no-op GC for performance testing (no memory
reclamation). |
|
|
Performance |
Flight Recorder (JFR) |
Low-overhead profiling tool now open-sourced. |
|
Improved String concatenation performance |
Uses invokedynamic internally. |
|
|
Deprecation/Removal |
Removed Java EE and CORBA modules |
These modules are no longer part of the JDK. |
|
Deprecated Nashorn JavaScript Engine |
Planned for removal in future versions. |
|
|
HTTP |
Standardized HTTP Client API (java.net.http) |
Introduced as incubator in Java 9; now fully
standard in Java 11. |
|
Launch Enhancements |
Running single-file source-code programs |
java HelloWorld.java – No need to compile
separately. |
|
Security |
TLS 1.3 Support |
Improved security and performance in SSL/TLS
communications. |
|
Miscellaneous |
Unicode 10 support |
Supports latest character sets and emojis. |
|
Local-Variable Syntax for Lambda Parameters |
Supports var for lambda parameters (enhanced
type inference). |
|
Feature |
Description |
Notes / Example |
|
Sealed Classes (JEP 409) |
Allows classes and interfaces to control
which other classes can extend or implement them. |
sealed interface Shape permits Circle, Square |
|
Pattern Matching for switch (Preview – JEP
406) |
Enhances switch so it can match patterns,
making code more concise and safe. |
switch (obj) { case String s -> ... } |
|
New macOS Rendering Pipeline (JEP 382) |
Introduced a new graphics pipeline for macOS
using Apple’s Metal API. |
Improves graphics performance on macOS. |
|
Strong Encapsulation of JDK Internals (JEP
403) |
Internal JDK APIs are strongly encapsulated,
except for critical sun.misc.Unsafe. |
Encourages use of standard APIs. |
|
Deprecating Security Manager (JEP 411) |
Security Manager and API marked for removal
in future versions. |
Consider alternatives like containers. |
|
Foreign Function & Memory API (Incubator
– JEP 412) |
Provides a pure Java API to interact with
native code and memory without JNI. |
Safer and easier than JNI. |
|
Vector API (Second Incubator – JEP 414) |
Provides API for expressing vector
computations to run efficiently on supported hardware. |
Example: SIMD optimizations. |
|
Deprecate RMI Activation (JEP 407) |
RMI Activation system deprecated and will be
removed. |
Encourages modern alternatives. |
|
Context-Specific Deserialization Filters (JEP
415) |
Improves security by allowing fine-grained
control over object deserialization. |
Helps mitigate serialization vulnerabilities. |
|
Other Changes |
- Removed experimental AOT/JIT compilers (JEP
410) - Removed Applet API (deprecated since Java 9) - Charset API updates |
Housekeeping & simplification. |
|
Category |
Feature |
Description |
|
Language Features |
Record Patterns
(finalized) |
Deconstruct records directly in pattern
matching. |
|
Pattern Matching for switch
(finalized) |
Enables type patterns and guarded patterns in
switch. |
|
|
String Templates
(preview) |
Simplifies string interpolation with template
expressions. |
|
|
Unnamed Classes and Instance main Methods |
Simplifies Java for beginner-friendly code
(preview). |
|
|
Scoped Values |
Safe, efficient alternatives to thread-local
variables. |
|
|
Virtual Threads & Concurrency |
Virtual Threads
(finalized) |
Lightweight threads to simplify
high-throughput concurrent programming. |
|
Structured Concurrency
(preview) |
Simplifies managing concurrent tasks in
structured blocks. |
|
|
Libraries & APIs |
Sequenced Collections |
Adds consistent ordering APIs to collections
(e.g., first(), last()). |
|
Key Encapsulation Mechanism (KEM)
APIs |
Adds new encryption APIs for modern
cryptographic use cases. |
|
|
Performance / VM |
Generational ZGC |
Adds generation support to ZGC for better
memory performance. |
|
Deprecations |
Deprecate Windows 32-bit x86 Port |
Marks the 32-bit Windows port for future
removal. |
|
Function |
Description |
Example |
|
count() |
Returns
the count of elements in the stream |
long
c = list.stream().count(); |
|
sum() |
Returns
the sum (only for primitive streams) |
int
s = list.stream().mapToInt(i -> i).sum(); |
|
min(Comparator) |
Returns
the minimum element using a comparator |
Optional<Integer>
min = list.stream().min(Integer::compare); |
|
max(Comparator) |
Returns
the maximum element using a comparator |
Optional<Integer>
max = list.stream().max(Integer::compare); |
|
average() |
Returns
the average of elements (primitive streams) |
OptionalDouble
avg = list.stream().mapToInt(i -> i).average(); |
|
reduce(identity,
accumulator) |
Reduces
elements to a single value with identity |
int
sum = list.stream().reduce(0, (a, b) -> a + b); |
|
reduce(accumulator) |
Same
as above but returns Optional<T> |
Optional<Integer>
total = list.stream().reduce((a, b) -> a + b); |
|
collect(Collectors.summarizingInt()) |
Returns
summary stats (count, sum, min, max, avg) |
IntSummaryStatistics
stats = list.stream().collect(Collectors.summarizingInt(i -> i)); |
|
collect(Collectors.joining()) |
Joins
string elements |
String
joined = list.stream().collect(Collectors.joining(", ")); |
|
groupingBy |
Group
elements by a classifier function and apply aggregation |
list.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting())); |
The Optional class in Java 8 is a container object used to contain not-null objects. Optional is part of the java.util package and was introduced to reduce the risk of NullPointerException and provide a better way to handle optional values.
|
Method |
Return
Type |
Description |
|
empty() |
Optional<T> |
Returns
an empty Optional instance. |
|
of(T
value) |
Optional<T> |
Returns
Optional with non-null value; throws NullPointerException if null. |
|
ofNullable(T
value) |
Optional<T> |
Returns
Optional of value or empty if null. |
|
get() |
T |
Returns
value if present; throws NoSuchElementException if not. |
|
isPresent() |
boolean |
Returns
true if value is present. |
|
ifPresent(Consumer<T>
action) |
void |
Executes
action if value is present. |
|
ifPresentOrElse(Consumer,
Runnable) |
void |
(Added
in Java 9)
Executes action if present, else runs Runnable. |
|
filter(Predicate<T>) |
Optional<T> |
Returns
same Optional if predicate matches, else empty. |
|
map(Function<T,R>) |
Optional<R> |
Applies
mapper function if value is present. |
|
flatMap(Function<T,
Optional<R>>) |
Optional<R> |
Similar
to map but avoids nested Optionals. |
|
orElse(T
other) |
T |
Returns
value if present; else returns other. |
|
orElseGet(Supplier<T>) |
T |
Returns
value if present; else returns value from Supplier. |
|
orElseThrow() |
T |
Returns
value if present; else throws NoSuchElementException. |
|
orElseThrow(Supplier<E>) |
T |
Returns
value or throws exception from supplier. |
Optional<String> name = Optional.of("Srikanth");
name.ifPresent(n -> System.out.println(n.toUpperCase()));
String result = name.orElse("Default");
System.out.println(result);
Optional<String> emptyName = Optional.empty();
String result2 = emptyName.orElse("Default");
System.out.println(result2);
When to Use Optional
ü As a return type when the result might be
absent.
ü To replace null checks.
ü To encourage functional-style programming
Lambda expressions provide a concise way to implement the abstract method of a functional interface.
Lambda expressions let you write shorter, cleaner, and more expressive code, especially for functional interfaces.
They are extensively used with Streams, Collections, and multithreading.
Functional interface is an interface that contains exactly one abstract method.
These interfaces are used primarily with lambda expressions and method references, enabling you to write cleaner and more concise code.
|
Functional Interfaces |
Example |
|
Function<T, R> |
Function<String,
Integer> lengthFunction = str -> str.length(); System.out.println(lengthFunction.apply("Sree")); |
|
BiFunction<T, U, R> |
BiFunction<Integer,
Integer, Integer> sum = (a, b) -> a + b; System.out.println(sum.apply(5, 3)); |
|
Consumer<T> |
Consumer<String>
consumer = name -> System.out.println("Hello, " + name); consumer.accept("Alice"); |
|
BiConsumer<T, U> |
BiConsumer<String,
Integer> print = (name, age) -> System.out.println(name + " is
" + age + " years old"); print.accept("Bob", 30); |
|
Supplier<T> |
Supplier<String>
supplier = () -> "Hello from Supplier!"; System.out.println(supplier.get()); |
|
Predicate<T> |
Predicate<String>
isLongerThan5 = s -> s.length() > 5; System.out.println(isLongerThan5.test("Hello")); |
|
BiPredicate<T, U> |
BiPredicate<String,
String> isEqual = (a, b) -> a.equalsIgnoreCase(b); System.out.println(isEqual.test("Java",
"java")); |
|
UnaryOperator<T> |
UnaryOperator<String>
toUpperCase = s -> s.toUpperCase(); System.out.println(toUpperCase.apply("hello")); |
|
BinaryOperator<T> |
BinaryOperator<Integer>
multiply = (a, b) -> a * b; System.out.println(multiply.apply(4, 5)); |
|
Runnable |
|
|
Callable |
|
|
Comparable |
|
|
Comparator |
|
functional interfaces are interfaces with a single abstract method (SAM), and they can be used as the target for lambda expressions or method references.
Annotated with @FunctionalInterface – this is optional, but it helps catch errors during
compile-time.
Predicate<Integer>
isEven = number -> number % 2 == 0;
System.out.println("Is
10 even? " + isEven.test(10));
Function<String,
Integer> stringLength = str -> str.length();
System.out.println("Length
of 'Hello': " + stringLength.apply("Hello"));
|
Aspect |
Comparable |
Comparator |
|
Package |
java.lang |
java.util |
|
Purpose |
Defines
natural ordering of objects |
Defines
custom ordering of objects |
|
Method |
int
compareTo(T o) |
int
compare(T o1, T o2) |
|
Implemented
By |
The
class itself |
A
separate class or lambda |
|
Affects
Original Class? |
Yes
– class must implement it |
No –
can be defined externally |
|
Used
With |
Collections.sort(list)
or Arrays.sort(array) |
Same,
with custom comparator passed as argument |
|
Java
8 Enhancements |
No
major change |
Supports
lambda expressions and default methods like comparing,
thenComparing |
|
Example
Use Case |
Sorting
employees by id (natural order) |
Sorting
employees by name, salary, etc. (custom) |
Comparator
in Java 8 is more powerful. You can use static methods like:
Ø Comparator.comparing()
Ø Comparator.thenComparing()
Ø Comparator.reversed()
people.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
people.forEach(person
-> System.out.println(person.getName()));
List<Integer>
sortedArrayList = al.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
int k = 2;
System.out.println(sortedArrayList.get(k-1));
A method reference is essentially a shorthand notation for
calling a method using a lambda expression.
Method references can be used in the context of functional interfaces
(interfaces with a single abstract method), commonly used in places where lambda
expressions are applicable.
Types of Method References
Reference to a Static Method
A static method in a class can be referred to with
ClassName::staticMethodName.
Reference to an Instance Method of a Particular Object
You can refer to an instance method of an object using
objectInstance::instanceMethodName.
Reference to an Instance Method of an Arbitrary Object of a Particular
Type
This is useful when you don't have a specific object but want to refer
to an instance method of an object of a specific type. It’s often used with Streams.
Reference to a Constructor
You can refer to a constructor using the ClassName::new syntax. This is
particularly useful when using factory methods or Streams.
Method references provide a more concise and expressive way to refer to
methods and are especially useful with Java's functional programming features
(like Streams). They can simplify your code by replacing lambda
expressions where the lambda body is just calling a method.
Cohesion is about how strongly the components of a single module/class are related to each other.
Coupling is about how dependent one module/class is on another.
|
Aspect |
Cohesion |
Coupling |
|
Definition |
Degree
to which elements inside a module belong together Measures how closely
related the responsibilities of a single class are. |
Degree
of interdependence between modules Measures how dependent
classes are on each other. |
|
Goal |
High
cohesion is
desirable |
Low
coupling is
desirable |
|
Focus |
Within
a class/module |
Between
classes/modules |
|
Improves |
Maintainability,
readability, testability |
Flexibility,
reusability, modularity |
|
Good
Example |
A
class that performs a single, well-defined task |
A
class that depends on interfaces, not implementations |
|
Bad
Example |
A
class that handles DB, UI, and business logic |
A
class that directly instantiates and uses other classes |
The Java Virtual Machine (JVM) memory model is a crucial concept for understanding how Java applications run. It manages memory in several distinct regions, each serving a specific purpose. Here's an overview of the key memory areas: Heap, Stack, and Metaspace.
+------------------------------+
| Method Area (Metaspace) |
+------------------------------+
| Heap |
+------------------------------+
| Stack |
+------------------------------+
| Program Counter (PC) |
+------------------------------+
| Native Method Stack |
+------------------------------+
|
Area |
Description |
|
Heap |
Stores objects and class instances. |
|
Stack |
Stores method frames, local variables. |
|
Metaspace (Java 8+) |
Stores class metadata, static methods, and constants. |
|
Method Area (part of
Metaspace) |
Stores class-level data like static variables, method info, and the
string constant pool. |
+----------------------------------------------+
| JVM Memory |
+----------------------+-----------------------+
| Heap | Metaspace |
| (for objects) | (replaces PermGen) |
| | |
| +---------------+ | +-----------------+ |
| | String Objects| | | String Constant | |
| | (e.g., new | | | Pool | |
| | String("a")) | | | ("a", "b", etc) | |
| +---------------+ | +-----------------+ |
| | |
| | +-----------------+ |
| | | Static final | |
| | | constants | |
| | | (e.g. int MAX = 5| |
| | | if inlined) | |
| | +-----------------+ |
+----------------------+-----------------------+
|
GC Algorithm |
Pause Time |
Throughput |
Heap Size
Suitability |
Multithreaded |
Concurrency |
|
Serial |
High |
Low |
Small |
❌ No |
❌ No |
|
Parallel |
Medium |
High |
Medium to Large |
✅ Yes |
❌ No |
|
CMS |
Low |
Medium |
Medium |
✅ Yes |
✅ Partial |
|
G1 |
Low-Medium |
High |
Medium to Large |
✅ Yes |
✅ Partial |
|
ZGC |
Very Low |
High |
Huge (>1TB) |
✅ Yes |
✅ Full |
|
Shenandoah |
Very Low |
High |
Large |
✅ Yes |
✅ Full |
JVM
options for GC logging:
-Xlog:gc*
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
|
Principle |
Benefit |
|
Final class |
Prevents subclass modification |
|
Private final fields |
Prevents field mutation |
|
Constructor initialization |
Full object initialization |
|
No setters |
Ensures immutability |
|
Defensive copies |
Avoid shared mutable state |
|
Immutable data structures |
Safer multithreaded use |
|
Feature |
synchronized |
ReentrantLock |
ExecutorService |
|
Locking Type |
Intrinsic (object/class) |
Explicit (manual control) |
Task Execution & Thread Management |
|
Unlock Requirement |
Automatic |
Manual (unlock()) |
Not applicable |
|
Fairness |
No |
Optional (new ReentrantLock(true)) |
Depends on pool |
|
Try Lock / Timeout |
No |
Yes (tryLock(), tryLock(timeout)) |
Not applicable |
|
Interruptible |
No |
Yes |
Yes (task cancellation APIs) |
|
Use Case |
Simple locking |
Complex locking scenarios |
Async task execution |
|
Step |
Description |
|
1️⃣ |
When you put a
key-value pair, the key’s hashCode() is calculated. |
|
2️⃣ |
That hashCode is
used to compute the index (bucket) using index = hash % capacity. |
|
3️⃣ |
If the bucket is
empty, the new node is stored directly. |
|
4️⃣ |
If the bucket
already has a node, equals() is used to check for duplicates. |
|
5️⃣ |
If equals() returns
true, value is updated; otherwise, a new node is added to the chain
(linked list or tree). |
|
6️⃣ |
When a bucket’s
chain becomes too long (threshold = 8), it's converted into a TreeNode
(Red-Black Tree) for faster access. |
|
7️⃣ |
When you call
get(key), it computes the hashCode() and index, then finds the node by
checking keys with equals(). |
|
8️⃣ |
If key found ➝
returns value, else ➝ returns null. |
|
9️⃣ |
HashMap resizes
(doubles capacity) when the size exceeds threshold = capacity * loadFactor.
Default load factor = 0.75. |
ConcurrentHashMap is a thread-safe and highly concurrent implementation of a hash map in Java. It allows multiple threads to read and write without locking the entire map.
|
Step |
Description |
|
1️⃣ |
ConcurrentHashMap
uses segments internally in Java 7, but buckets with Node arrays +
CAS locking in Java 8+. |
|
2️⃣ |
When inserting
(put()), the key’s hashCode() is computed to determine the bucket
index. |
|
3️⃣ |
If the bucket is empty,
a new node is inserted using CAS (Compare-And-Swap) to ensure
thread-safety. |
|
4️⃣ |
If the bucket is not
empty, threads use fine-grained locking only on that particular
bucket/node. |
|
5️⃣ |
If multiple threads
try to write to the same bucket, only one thread locks that bucket —
not the entire map. |
|
6️⃣ |
If hash collisions
occur, nodes are stored in a linked list, and converted to tree
nodes (like HashMap) if they grow beyond threshold (8). |
|
7️⃣ |
For reads (get()),
it uses volatile reads, so it’s mostly lock-free — giving
excellent performance. |
|
8️⃣ |
Resizing is thread-safe and done using transfer bins
where threads help in rehashing |
ü HashMap is not thread-safe and may produce inconsistent results in
multithreaded environments.
ü ConcurrentHashMap allows concurrent access with thread safety
using internal segment locking.
A thread-safe class or method ensures that shared data is accessed and modified in a controlled and predictable manner. If two or more threads use it simultaneously, it will function correctly without needing additional synchronization from the user.
|
Technique |
Thread Safety |
Use Case |
|
synchronized |
✅ Yes |
Simple critical
section control |
|
java.util.concurrent |
✅ Yes |
Collections and
utilities |
|
Atomic variables |
✅ Yes |
Lock-free counters,
flags |
|
Immutable objects |
✅ Yes |
Data that never
changes |
|
Thread-local storage |
✅ Yes |
Per-thread variable
isolation |
|
Locks
(ReentrantLock) |
✅ Yes |
Fine-grained
locking, tryLock, fairness, etc. |
ü It is the implementation class of Lock interface and
direct child class of object.
ü Reentrant means a thread can acquire same lock
multiple times without any issue.
Implementing a thread-safe LRU (Least Recently Used) cache in Java can be done in several ways. Here's a breakdown of the most common and effective approach using:
Approach: Use LinkedHashMap with synchronization
ü LinkedHashMap maintains insertion/access order.
ü Override removeEldestEntry to implement LRU
eviction.
ü Add synchronization or use
Collections.synchronizedMap() or ReentrantReadWriteLock for thread safety.
It make use of the fork-join framework and its common pool of worker threads.
It is a class in Java (java.util.concurrent) that allows you to write asynchronous, non-blocking code. It helps you run tasks in the background and then continue processing once they’re complete.
Rich async composition, chaining, non-blocking where as feature java5 feature and it will perform Simple async task with blocking result
CompletableFuture is part of java.util.concurrent that represents a future result of an asynchronous computation.
|
Step |
What Happens |
|
1️⃣ |
You call an async method like
supplyAsync() or runAsync() to start work in the background. |
|
2️⃣ |
Java spawns a new thread (from
ForkJoinPool or custom executor). |
|
3️⃣ |
When the task is done,
CompletableFuture is completed with a result or an exception. |
|
4️⃣ |
You can attach callbacks
like .thenApply(), .thenAccept(), .thenRun() to chain further actions. |
|
5️⃣ |
You can also combine
multiple futures using .thenCombine(), .allOf(), .anyOf(), etc. |
|
6️⃣ |
Finally, you can block
using .get() (if needed) or handle exceptions using .exceptionally(). |
ü
Memory leaks happen when
objects are no longer in use but are still referenced.
ü
Tools: VisualVM, Eclipse
MAT, JProfiler.
ü
Common causes: static
collections, listeners not removed, inner classes holding outer class
references.
ü
Fix: Ensure objects are
dereferenced properly, use WeakReference when appropriate.
1. Use Modern Java Concurrency APIs (Avoid Thread and synchronized)
2. Prefer ForkJoinPool for Parallel Processing
3. Use CompletableFuture for Asynchronous Programming
4. Avoid Race Conditions with Atomic Variables or Locks
5. Avoid Deadlocks by Lock Ordering
6. Use ThreadLocal for Thread-Specific Data
7. Use ScheduledExecutorService for Periodic Tasks
8. Use Non-Blocking I/O (NIO) for High-Performance Applications
9. Prefer Virtual Threads (Java 21) Over Traditional Threads
10. Monitor and Tune Thread Performance
Microservice design patterns help build robust, scalable, and maintainable microservice-based systems. These patterns address common challenges such as service communication, data consistency, fault tolerance, scalability, and more.
|
Pattern Category |
Design Pattern |
Description |
Spring Boot Implementation |
|
Decomposition |
Decompose by Business Capability |
Split services by domain/subdomain based on business logic |
Use Spring Boot projects for each domain like order-service,
user-service, etc. |
|
Decompose by Subdomain |
Align services with bounded contexts from Domain-Driven Design
(DDD) |
Use Spring Boot with DDD principles, splitting services like
inventory-service, catalog-service. |
|
|
Integration |
API Gateway |
Single entry point for all microservices |
Use Spring Cloud Gateway or Zuul Proxy to route requests
to backend services. |
|
Aggregator |
Combines responses from multiple services |
Create a composite Spring Boot service that calls multiple
downstream REST endpoints. |
|
|
Backend for Frontend (BFF) |
Different APIs for different front-end clients |
Use separate Spring Boot apps or controllers for mobile, web,
etc. with client-specific logic. |
|
|
Database |
Database per Service |
Each microservice owns its database |
Use Spring Data JPA or Spring JDBC with separate
schema per microservice. |
|
Shared Database |
Multiple services access the same DB (anti-pattern in most cases) |
If used, ensure transaction management and data consistency
using Spring Boot. |
|
|
Reliability |
Circuit Breaker |
Prevent cascading failures |
Use Resilience4j or Hystrix with Spring Boot to wrap
service calls and define fallback methods. |
|
Retry |
Retry failed requests automatically |
Use Spring Retry with declarative annotations like @Retryable,
@Recover. |
|
|
Timeout |
Set time limits on service calls |
Configure timeouts in RestTemplate/WebClient or Feign
clients. |
|
|
Bulkhead |
Isolate failures to prevent service-wide impact |
Use Resilience4j Bulkhead in Spring Boot apps for isolation. |
|
|
Observability |
Log Aggregation |
Centralize logs from all services |
Use Spring Boot + Logback + ELK (Elasticsearch, Logstash,
Kibana) stack. |
|
Distributed Tracing |
Trace a request across services |
Use Spring Cloud Sleuth with Zipkin or OpenTelemetry. |
|
|
Metrics Collection |
Monitor performance metrics |
Integrate Micrometer with Prometheus + Grafana in Spring
Boot. |
|
|
Cross-Cutting |
External Configuration |
Manage config separately from code |
Use Spring Cloud Config Server or Vault for dynamic
configuration. |
|
Service Discovery |
Services find each other automatically |
Use Eureka Server or Consul with Spring Boot clients. |
|
|
Centralized Security |
Secure APIs and handle authentication centrally |
Use Spring Cloud Gateway with OAuth2 (Keycloak, Auth0,
Okta) for centralized access control. |
|
|
Data Consistency |
Saga Pattern |
Manage distributed transactions via events or orchestration |
Use Spring Boot + Kafka/RabbitMQ and implement saga
orchestration or choreography using state machines. |
|
Event Sourcing |
Store changes as events instead of final state |
Use Spring Boot + Event Store (Kafka, Axon Framework) to track and
replay state changes. |
|
|
CQRS (Command Query Responsibility Segregation) |
Separate read/write models |
Use different Spring Boot services/models for reading and writing;
implement with Axon Framework if needed. |
|
|
Messaging |
Message Broker |
Use messaging for asynchronous communication |
Integrate Spring Boot with Apache Kafka, RabbitMQ,
or ActiveMQ using @KafkaListener, etc. |
|
Publish-Subscribe |
Broadcast eventsto multiple consumers |
Use Kafka topics with multiple Spring
Boot consumers for pub/sub model. |
|
Pattern |
Type |
Where It’s Used
in Spring Boot / Microservices |
Typical Use Case
/ Example |
|
Singleton |
Creational |
Spring Beans (@Component, @Service) |
Ensure a single instance of a service or component |
|
Factory Method |
Creational |
ApplicationContext, BeanFactory, @Bean |
Creating beans dynamically; customizing object creation |
|
Builder |
Creational |
DTOs, Response objects, Fluent APIs |
Constructing complex response objects (e.g., UserResponse.builder()) |
|
Prototype |
Creational |
Spring’s @Scope("prototype") |
For creating new bean instances per request (e.g., PDF generator) |
|
Adapter |
Structural |
Spring Security (UserDetailsAdapter), Legacy integration |
Adapting incompatible interfaces (e.g., external API to internal
model) |
|
Decorator |
Structural |
Custom logging, validation wrappers |
Add functionality to methods like input validation or logging |
|
Proxy |
Structural |
AOP (@Transactional, @Cacheable) |
Add cross-cutting concerns like caching, security, transactions |
|
Template Method |
Behavioral |
JdbcTemplate, RestTemplate, TransactionTemplate |
Abstract steps of a process with hook methods for customization |
|
Strategy |
Behavioral |
Payment/Authentication strategies, dynamic algorithms |
Select logic at runtime (e.g., choosing a payment method) |
|
Observer |
Behavioral |
ApplicationEventPublisher, @EventListener |
Publish/subscribe model for events (e.g., send email on user
registration) |
|
Command |
Behavioral |
Background jobs, task queues, CQRS pattern |
Encapsulate request/command logic (e.g., order submission) |
|
Chain of
Responsibility |
Behavioral |
Servlet Filter chains, Spring Security filters |
Pass request through a chain of filters/middleware |
|
Facade |
Structural |
Service Layer, API Gateway in microservices |
Provide a simplified interface to a complex system |
|
Interpreter |
Behavioral |
Expression parsing in business rules or DSLs |
Evaluate and interpret dynamic business rules (rare) |
|
Iterator |
Behavioral |
Paging large datasets using JPA or Streams |
Iterating collections of data (e.g., page through results) |
|
Pattern |
Category |
Use Case |
|
Circuit Breaker |
Resilience |
Handle service
failure gracefully (e.g., Resilience4j) |
|
API Gateway |
Architectural |
Entry point for all
requests (e.g., Zuul, Spring Cloud Gateway) |
|
Service Registry |
Discovery |
Register/discover
services (e.g., Eureka) |
|
Saga |
Transaction Mgmt |
Handle distributed
transactions across services |
|
Bulkhead |
Resilience |
Isolate services to
prevent cascading failures |
|
Retry / Timeout |
Resilience |
Retry failed calls
(e.g., Resilience4j Retry) |
The 12-Factor App methodology provides best practices for building scalable, maintainable, and portable web applications, especially useful when designing microservices. Here’s a breakdown of the 12 factors and how they relate to microservice architecture:
Ø One codebase tracked in version control, many
deploys.
Ø Each microservice should have its own
repository (or clearly separated module) with a single source of truth.
Ø
Explicitly
declare and isolate dependencies.
Ø
Use a dependency manager
(like pip, npm, Maven, etc.) to declare exact
dependencies.
Ø
Avoid relying on
system-wide packages.
Ø
Store
config in the environment.
Ø
Use environment
variables for things like DB credentials, API keys, or feature flags.
Ø
Keeps code portable between
environments (dev, staging, production).
Ø
Treat
backing services as attached resources.
Ø
Databases, queues, caches,
etc., should be replaceable without code changes.
Ø
Access via URLs or
environment configs.
Ø Strictly separate build and run stages.
Ø
Your delivery
pipeline should clearly separate:
ü
Build (compile code)
ü
Release (combine build + config)
ü
Run (run the app with the release)
Ø Execute the app as one or more stateless processes.
Ø
Microservices
should be stateless. Any state (e.g., sessions) should be stored in external
services like Redis or databases.
Ø Export services via port binding.
Ø
Each
microservice should be a self-contained unit exposing a port and
listening for requests (e.g., HTTP/REST, gRPC).
Ø Scale out via the process model.
Ø
Design services
to scale horizontally by spawning more instances (e.g., using
Docker/Kubernetes).
Ø Fast startup and graceful shutdown.
Ø
Microservices
should be resilient and quick to start/stop for dynamic scaling
and updates.
Ø Keep development, staging, and production as
similar as possible
Ø
Minimize the
gap between environments to reduce bugs caused by environment-specific issue
Ø
Treat
logs as event streams.
Ø
Write logs to stdout/stderr,
and use a log aggregator (like ELK stack, Loki, etc.) to handle storage and
analysis.
Ø
Run
admin/management tasks as one-off processes.
Ø
For tasks like DB
migrations, use scripts or jobs that can be run independently from the
app processes.
Ø The 12-Factor App methodology provides best practices for building scalable, maintainable, and portable web applications, especially useful when designing microservices. Here’s a breakdown of the 12 factors and how they relate to microservice architecture:
|
Factor |
Description |
Spring Boot Implementation / Best Practices |
|
1. Codebase |
One codebase tracked in version control per app. |
One Git repo per microservice; use Git, GitHub/GitLab. |
|
2. Dependencies |
Explicitly declare and isolate dependencies. |
Use pom.xml or build.gradle for dependency management. |
|
3. Config |
Store config in the environment, not in code. |
Use application.properties / application.yml, externalize with Spring
Cloud Config or env variables. |
|
4. Backing Services |
Treat backing services as attached resources. |
Configure databases, caches, messaging via properties or discovery
(e.g., RabbitMQ, Redis). |
|
5. Build, Release, Run |
Strictly separate build and run stages. |
Use CI/CD tools (e.g., Jenkins, GitHub Actions); package with Docker. |
|
6. Processes |
Run the app as one or more stateless processes. |
Design microservices to be stateless; use Spring Boot stateless
controllers and services. |
|
7. Port Binding |
Export services via port binding. |
Use embedded Tomcat and define ports in application.properties. |
|
8. Concurrency |
Scale out via the process model. |
Run multiple Spring Boot instances; scale using Docker/Kubernetes. |
|
9. Disposability |
Fast startup and graceful shutdown. |
Ensure quick start time and handle shutdown hooks in Spring Boot using
@PreDestroy. |
|
10. Dev/Prod Parity |
Keep development, staging, and production as similar as possible. |
Use same Docker images/configs across environments; use profiles (dev,
prod, etc.). |
|
11. Logs |
Treat logs as event streams. |
Use SLF4J/Logback; output to console; aggregate with ELK stack or
Grafana Loki. |
|
12. Admin Processes |
Run admin/management tasks as one-off processes. |
Use Spring Boot Actuator for health checks, metrics; run DB migrations
with Flyway/Liquibase. |
SAGA is a sequence of
local transactions where each transaction updates data within a single
service and publishes an event or command to trigger the next
transaction. If one of the steps fails, it triggers compensating
transactions to undo the changes made by the previous steps.
These priniciples are used
to manage long running and distributed transactions.
There are two main types:
Why Use SAGA?
Distributed systems can't easily use ACID transactions across multiple services or databases. SAGA helps
Ø Maintain eventual consistency
Ø ✅
Avoid distributed locks
Ø ✅
Support scalability
✅ Improve resilience via compensating
transactions
|
Principle |
Definition |
Java Code Example |
Real-life Analogy |
|||
|
S - Single
Responsibility Principle |
A class should have one and only one reason to change. |
Employee class only stores data; a separate EmployeePrinter class
handles printing. |
Think of a restaurant: the chef cooks, the cashier handles bills – one
role, one responsibility. |
|||
|
O - Open/Closed
Principle |
Software entities should be open for extension but closed for
modification. |
Use interfaces or abstract classes. Add new shapes without modifying
the existing drawing code. |
A power strip lets you add more devices without changing the wall
socket. |
|||
|
L - Liskov
Substitution Principle |
Subclasses should be substitutable for their base classes. |
Bird class has fly(), but Penguin (which can’t fly) shouldn’t extend
it. Instead, use interfaces like Flyable. |
You can replace a regular printer with a new model and it still
prints. |
|||
|
I - Interface
Segregation Principle |
Don’t force a class to implement interfaces it doesn’t use. |
Split Machine interface into Printer, Scanner, Fax interfaces. Don’t
force all-in-one. |
ATM machine’s screen and keypad have different interfaces for
different tasks. |
|||
|
D – Dependency Inversion |
High-level modules should not depend on low-level modules, but on
abstractions |
@Autowired
NotificationService (interface) instead of concrete class. Inject via Spring
for flexibility and testing. |
||||
|
Design Principle |
Description /
Usage in Spring Boot |
|
1. SOLID Principles |
Foundation of object-oriented design: - Single Responsibility -
Open/Closed - Liskov Substitution - Interface
Segregation - Dependency Inversion |
|
2. Dependency Injection (DI) |
Spring’s core feature; promotes loose coupling by injecting beans via
constructor/setters. |
|
3. Inversion of Control (IoC) |
Objects do not create dependencies; Spring controls the instantiation
lifecycle. |
|
4. Separation of Concerns (SoC) |
Split application into layers: Controller, Service, Repository, etc. |
|
5. Convention over Configuration |
Spring Boot auto-configuration reduces the need for manual XML config. |
|
6. Don’t Repeat Yourself (DRY) |
Reuse services,
components, and configuration where possible. |
|
7. High Cohesion & Low Coupling |
Classes should do
one thing well (cohesion) and depend minimally on others (low coupling). |
|
8. Configuration as Code |
Use application.yml,
@ConfigurationProperties, and @Value instead of hardcoding. |
|
9. Fail Fast |
Spring Boot fails
app startup if required beans/configs are missing, enabling early error
detection. |
|
10. Profiles for Environments |
Use @Profile and
application-{profile}.yml to separate dev, QA, prod configurations. |
|
Term |
Description |
|
||
|
Pod |
The smallest deployable unit in K8s, usually contains one or more containers. |
|
||
|
Node |
A physical or virtual machine that runs pods. |
|
||
|
Cluster |
A set of nodes managed by Kubernetes. |
|
||
|
Deployment |
Manages stateless applications and ensures desired state of pods is
maintained. |
|
||
|
StatefulSet |
Manages stateful applications with persistent identity and storage. |
|
||
|
DaemonSet |
Ensures a pod runs on all (or some) nodes. |
|
||
|
ReplicaSet |
Maintains a stable set of replica pods running at any given time. |
|
||
|
Job |
Runs a batch task to completion. |
|
||
|
CronJob |
Schedules Jobs to run periodically at fixed times. |
|
||
|
Service |
Exposes a set of pods as a network service. |
|
||
|
Ingress |
Manages external HTTP/HTTPS access to services. |
|
||
|
ConfigMap |
External configuration for pods as key-value pairs. |
|
||
|
Secret |
Stores sensitive data like passwords or tokens. |
|
||
|
Namespace |
Virtual cluster within a cluster to divide resources. |
|
||
|
Kubelet |
Agent running on each node, manages the pod lifecycle. |
|
||
|
Kube-proxy |
Manages networking rules on nodes to route traffic. |
|
||
|
API Server |
Frontend for Kubernetes control plane; processes REST commands. |
|
||
|
Controller
Manager |
Runs controllers like ReplicationController and handles state
reconciliation. |
|
||
|
Scheduler |
Assigns newly created pods to nodes. |
|
||
|
Helm |
Package manager for Kubernetes (like apt or yum). |
|
||
|
Volume |
Directory accessible to containers for persistent or shared storage. |
|
||
|
PersistentVolume
(PV) |
A piece of storage in the cluster provisioned by an admin. |
|
||
|
PersistentVolumeClaim
(PVC) |
A user’s request for storage resources. |
|
||
|
Label |
Key-value pair used to organize and select Kubernetes resources. |
|
||
|
Selector |
Used to identify a group of objects by their labels. |
|
||
|
Taint &
Toleration |
Used to control which pods can be scheduled on which nodes. |
|
||
|
Docker |
Core Concept |
Open platform to build, ship, and run applications in containers |
||
|
Container |
Runtime |
Lightweight, isolated environment to run applications with all dependencies |
||
|
Image |
Build |
Read-only template with instructions to create a container |
||
|
Dockerfile |
Build |
Script containing instructions to
build a Docker image |
||
|
Docker Engine |
Runtime |
Core component that runs and manages containers |
||
|
Docker Hub |
Registry |
Cloud-based registry to store and share Docker images |
||
|
Docker Compose |
Orchestration |
Tool for defining and running multi-container Docker applications using docker-compose.yml |
||
This is the brain of the Kubernetes cluster. It manages the cluster and orchestrates all the activities.
Responsibilities:
ü
Scheduling
pods on worker nodes
ü
Monitoring
node and pod health
ü
Managing
scaling and healing (e.g., restarting failed pods)
ü
Maintaining
cluster state in etcd
These are the machines where your application runs — they host the containers.
Responsibilities:
ü
Run
workloads (Pods)
ü
Communicate
with the master node
ü
Report
node health and resource usage
ü
Pull
container images and manage container lifecycle
Spring Security is a powerful and customizable authentication and access control framework for Java applications, especially Spring-based ones.
It uses filters (like UsernamePasswordAuthenticationFilter, BasicAuthenticationFilter, etc.) in a specific order within the filter chain to handle authentication and authorization.
ü
Authentication: Verifying identity (e.g.,
username/password).
ü
Authorization: Granting access to resources based on
roles/permissions.
It's a chain of filters through which every request
passes. Each filter has a responsibility like authenticating the user or
checking CSRF. (Cross-Site Request Forgery)
|
SecGateway |
Oauth2.0 (public api) |
|
Governance |
JWT (with in intranet) |
A JWT is a compact, URL-safe token used for stateless authentication. It contains a header, payload, and signature.
ü
Header: Algorithm and token type.
ü
Payload: Claims (e.g., user id, roles).
ü
Signature: Verifies token integrity.
Claims are key-value pairs in the payload that carry user-related data (e.g., sub, roles, exp).
JWT is created during login and returned to the client. For subsequent requests, the client sends the JWT in the Authorization header, and the backend verifies it using a filter.
ü
Disable session management
(STATELESS)
ü
Add JWT filters for
login/authentication
ü
Use UsernamePasswordAuthenticationFilter and OncePerRequestFilter
ü
Create JwtUtil to generate and validate
tokens
It ensures the filter logic runs once per request. Ideal for JWT validation and authentication population
Inside a custom OncePerRequestFilter, often called JwtAuthenticationFilter.
By implementing AuthenticationEntryPoint to handle 401 Unauthorized responses for invalid or missing JWTs.
Use exp claim to expire tokens. Implement a refresh token endpoint to issue new tokens without asking for credentials again.
JWT is secure if
signed and stored properly. Risks include:
ü
Token
theft if stored in localStorage
ü
No token
revocation mechanism
ü
Susceptibility
to replay attacks
Include roles in the JWT payload and check them using hasRole() or hasAuthority() in controller methods.
Enables Spring Security for the application and allows custom configuration.
ü @PreAuthorize: SpEL-based expression (e.g.,
@PreAuthorize("hasRole('ADMIN')"))
ü @Secured: Simpler, only supports role checks.
It holds the currently authenticated user's details and authorities during the request lifecycle.
CSRF protection is typically disabled for stateless APIs using JWT, since there's no session.
http.csrf().disable();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
ü JwtUtil – For token creation and validation
ü JwtAuthenticationFilter – Extends
OncePerRequestFilter
ü UserDetailsServiceImpl – Loads user from DB
ü SecurityConfig – Defines custom filter chain
and disables sessions
[ Client (SPA/Mobile) ]
|
| POST /login (username + password)
V
[ Spring Boot Auth Server ]
|
| Returns JWT (signed)
V
[ Client stores JWT (e.g. localStorage) ]
|
| Authorization: Bearer <JWT>
V
[ Protected Resource/API (Spring Security validates JWT) ]
[ Client (SPA/Mobile) ]
|
| Redirect to Google Auth URL
V
[ Google Auth Server ]
|
| User logs in, consents
V
[ Redirect to Backend with Auth Code ]
|
| Backend exchanges code for JWT token
V
[ Use Access Token to access Resource API ]
|
Feature |
OAuth 1.0 |
OAuth 2.0 |
|
Specification Type |
Protocol |
Framework |
|
Token Type |
Encrypted tokens (not readable) |
Bearer tokens (optionally JWTs) |
|
Token Security |
Requires cryptographic signatures (HMAC-SHA1) |
Uses HTTPS for security; no signatures in most cases |
|
Token Format |
Opaque |
Opaque or JWT (flexible) |
|
Ease of Use |
Complex (requires signature generation on client) |
Simpler, supports different grant types |
|
Client Types Supported |
Mainly web-based apps |
Web, mobile, desktop, IoT apps |
|
Token Revocation |
Not standardized |
Supported |
|
Scopes |
Limited support |
Built-in with fine-grained access via scopes |
|
Refresh Tokens |
Not supported |
Supported |
|
Backwards Compatible |
N/A |
Not compatible with OAuth 1.0 |
|
Scenario |
Recommendation |
|
Legacy APIs
(Twitter, old APIs) |
Use OAuth 1.0a (if
required) |
|
New applications |
Always use OAuth 2.0 |
|
Need mobile, SPA,
or microservice support |
OAuth 2.0 |
|
Need refresh
tokens and multiple flows |
OAuth 2.0 |
|
Category |
Term |
Description |
Applicable To |
|
Token Basics |
JWT (JSON Web Token) |
A compact, URL-safe token format containing claims (data) used for
authentication and authorization |
JWT, OAuth 2.0 |
|
Access Token |
Token used to access protected resources; short-lived |
OAuth 2.0, JWT |
|
|
Refresh Token |
Token used to obtain a new access token without re-authenticating |
OAuth 2.0 |
|
|
ID Token |
Token that contains identity information about the user (OpenID
Connect) |
OAuth 2.0 (OIDC) |
|
|
JWT Structure |
Header |
Metadata about the token, including type and signing algorithm (alg,
typ) |
JWT |
|
Payload |
Contains claims (e.g., sub, iat, exp, aud) |
JWT |
|
|
Signature |
Used to verify the token’s integrity using a secret or public key |
JWT |
|
|
Token Claims |
iss (Issuer) |
Entity that issued the token |
JWT |
|
sub (Subject) |
Unique identifier for the user |
JWT |
|
|
aud (Audience) |
Intended recipient of the token |
JWT |
|
|
exp (Expiration) |
Expiration time of the token |
JWT |
|
|
iat (Issued At) |
Timestamp of when token was issued |
JWT |
|
|
nbf (Not Before) |
Token is not valid before this time |
JWT |
|
|
OAuth Roles |
Resource Owner |
The user who authorizes access to a resource |
OAuth 2.0 |
|
Client |
The app requesting access to a resource |
OAuth 2.0 |
|
|
Authorization Server |
Issues tokens after authentication and authorization |
OAuth 2.0 |
|
|
Resource Server |
Hosts protected APIs/resources, verifies access token |
OAuth 2.0 |
|
|
OAuth Grants |
Authorization Code |
Used in server-side apps; secure and common |
OAuth 2.0 |
|
Implicit |
Used in SPAs; not recommended due to security concerns |
OAuth 2.0 |
|
|
Client Credentials |
Used for service-to-service authentication |
OAuth 2.0 |
|
|
Resource Owner Password |
Directly exchanges username/password for token; deprecated |
OAuth 2.0 |
|
|
Security Concepts |
Bearer Token |
Token passed in Authorization: Bearer <token> header |
OAuth 2.0, JWT |
|
Scope |
Defines what access the token allows (e.g., read, write) |
OAuth 2.0 |
|
|
PKCE (Proof Key for Code Exchange) |
Enhances security of authorization code grant in public clients |
OAuth 2.0 |
|
|
Token Revocation |
Invalidate a token before expiration |
OAuth 2.0 |
|
|
Spring Usage |
spring-security-oauth2 |
Library to implement OAuth2 clients and resource servers in Spring
Boot |
OAuth 2.0 |
|
@EnableResourceServer |
Configures the app to validate access tokens |
Spring OAuth |
|
|
@EnableAuthorizationServer |
Enables token issuing service (deprecated, prefer Spring Authorization
Server project) |
Spring OAuth |
+----------------+ +---------------------+ +------------------+
| User Agent | | Authorization Server| | Resource Server|
| (Browser/App) | | (e.g., Keycloak) | | (Spring Boot App)|
+--------+-------+ +----------+----------+ +--------+---------+
| | |
| 1. Authorization Request | |
|---------------------------->| |
| | |
| 2. Login & Consent | |
|<----------------------------| |
| | |
| 3. Auth Code Returned | |
|<----------------------------| |
| | |
| 4. Exchange Code for Token | |
|---------------------------->| |
| | |
| 5. Returns Access Token (JWT)| |
|<----------------------------| |
| | |
| 6. API Call with JWT | |
|---------------------------->| `Authorization: Bearer <JWT>` |
| | |
| 7. Token Verified | |
| |--> Validate Signature, Claims |
| | |
| 8. Protected Data Returned | |
|<----------------------------| |
Spring is a powerful
open-source framework for building Java applications.
It simplifies Java enterprise development by handling lots of heavy
lifting (like managing objects, database connections, transactions, etc.).
ü Make Java programming easier.
ü Promote good practices like Dependency
Injection (DI) and Aspect-Oriented Programming (AOP).
ü Provide a lightweight alternative to
Java EE (J2EE) applications.
In Spring, a Bean is just a normal
Java object (POJO) that is managed by Spring.Bean = an object
registered in the Spring container.
Ways to define a Bean:
ü Using @Component Annotation:
ü Using Java Configuration:
ü Using XML Configuration (older way):
The ApplicationContext
is the Spring Container that:
ü
Creates Beans
ü
Wires them together
ü
Manages their life cycle
ü
Provides utilities (like internationalization, events,
etc.)
ü ClassPathXmlApplicationContext
ü AnnotationConfigApplicationContext
ü WebApplicationContext (for Spring MVC)
ü
Objects do
not create their dependencies.
ü
Dependencies
are injected (provided) by the Spring container.
ü
Promotes
loose coupling.
ü Separate cross-cutting concerns like
logging, security, transactions.
ü You don't mix these concerns into your business
logic code.
ü
Sometimes you need to apply
common behavior across different parts of an app (e.g., logging, security
checks, transactions).
ü
Without AOP: You would duplicate
this logic in multiple classes.
ü
With AOP: You define it once
and apply it where needed automatically.
ü
ü @Aspect → Marks this class as an aspect.
ü @Before("execution(...)") → Runs before matched method
executes.
ü @After("execution(...)") → Runs after matched method completes
(even if it throws an exception).
ü "execution(* com.example.service.*.*(..))" →
Pointcut expression: match all methods in all classes under
com.example.service.
ü
The heart
of Spring.
ü
Manages
the life cycle and configuration of your application objects (called Beans).
ü
Uses
configuration files (XML) or Java Annotations (@Component, @Service, etc.).
Spring is not just one thing; it's a collection of modules.
ü
Create
Objects (Beans) and their
dependencies.
ü
Configure them (either via XML or Annotations).
ü
Spring
Container reads this configuration.
ü
Container
Instantiates the objects.
ü
Container
Injects Dependencies.
ü
Application
Runs with fully ready Beans.
Containers like BeanFactory and ApplicationContext manage all this.
ü
Lightweight: You don't have to write too much code.
ü
Flexible: You can pick only the parts you need.
ü
Loose
Coupling: Thanks to Dependency
Injection.
ü
Easy
Integration: Works well with other
frameworks (Hibernate, JPA, etc.).
ü
Powerful
Web Development: Using Spring MVC and
Spring Boot.
ü XML Configuration:
ü Annotation-Based Configuration:
ü Java-based Configuration (using @Configuration and @Bean):
Spring Boot is a framework designed to simplify the development of Java applications, particularly those built with the Spring Framework.
It provides:
ü Auto-configuration: Automatically configures your application
based on the dependencies in the classpath.
ü Standalone applications: You can run Spring Boot applications with a
simple main() method.
ü Embedded servers: No need to deploy WAR files—Spring Boot
includes Tomcat, Jetty, or Undertow as embedded web servers.
ü Production-ready features: Like health checks, metrics, and externalized
configuration.
|
Annotation |
Description |
|
@SpringBootApplication |
Combines
@Configuration, @EnableAutoConfiguration, and @ComponentScan |
|
@EnableAutoConfiguration |
Enables Spring
Boot’s auto-configuration mechanism |
|
@ComponentScan |
Scans the package
for Spring components (@Component, @Service, etc.) |
|
@Configuration |
Marks a class as a
source of bean definitions |
|
@Bean |
Declares a bean
manually inside a @Configuration class |
ü
Uses @EnableAutoConfiguration
and classpath scanning.
ü
Reads spring.factories to
auto-configure beans conditionally.
ü
Example: If DataSource
class is found, it configures a datasource.
ü
Can override with @ConditionalOnMissingBean,
custom @Configuration.
|
Annotation |
Description |
|
@Component |
Generic
Spring-managed component |
|
@Service |
Marks a class as a
service layer component |
|
@Repository |
Marks a class as a
DAO/repository component |
|
@Controller |
Marks a class as a
web controller |
|
@RestController |
Combines @Controller
+ @ResponseBody |
|
Annotation |
Description |
|
@Autowired |
Injects a dependency by type |
|
@Qualifier |
Used with @Autowired to resolve ambiguity |
|
@Value |
Injects values from application properties |
|
Scenario |
Why Use
@Qualifier? |
|
Multiple @Service or
@Component of same interface |
To inject a specific
one |
|
Multiple @Bean
definitions |
To differentiate
them |
|
Multiple
implementations of repository or strategy pattern |
For flexibility and
testing |
|
When integrating
third-party APIs |
Inject appropriate
handler |
ü @Qualifier is used to resolve ambiguity
when multiple beans of the same type are present.
|
Annotation |
Description |
|
@RequestMapping |
Maps HTTP requests to handler methods/classes |
|
@GetMapping |
Shortcut for @RequestMapping(method = GET) |
|
@PostMapping |
Shortcut for @RequestMapping(method = POST) |
|
@PutMapping |
Shortcut for @RequestMapping(method = PUT) |
|
@DeleteMapping |
Shortcut for @RequestMapping(method = DELETE) |
|
@PathVariable |
Binds URL path variables to method parameters |
|
@RequestParam |
Binds request parameters (query strings) |
|
@RequestBody |
Binds request body to a method parameter |
|
@ResponseBody |
Returns object data as response body (JSON, etc.) |
|
@CrossOrigin |
Enables CORS for controller/method |
|
Annotation |
Description |
|
@Entity |
Marks a class as a
JPA entity |
|
@Table |
Maps the entity to a
database table |
|
@Id |
Marks the primary
key |
|
@GeneratedValue |
Specifies
auto-generation strategy for ID |
|
@Column |
Maps a field to a
table column |
|
@Repository |
Marks the interface
as a Spring Data repository |
|
@Query |
Custom JPQL/native
SQL query |
|
Annotation |
Description |
|
@Valid |
Triggers validation
on method arguments |
|
@NotNull |
Field must not be
null |
|
@NotBlank |
Field must not be
null or empty (String) |
|
@Min, @Max |
Specifies numeric
constraints |
|
@Size |
Specifies size
limits for collections or strings |
|
Annotation |
Description |
|
@Aspect |
Declares a class as
an AOP aspect |
|
@Before |
Runs before the
matched method execution |
|
@After |
Runs after the
method execution |
|
@AfterReturning |
Runs after a method
returns successfully |
|
@AfterThrowing |
Runs if method
throws an exception |
|
@Around |
Surrounds method
execution (pre & post) |
|
Annotation |
Description |
|
@SpringBootTest |
Loads full Spring
Boot context for integration tests |
|
@WebMvcTest |
Loads only web layer
(controllers) |
|
@DataJpaTest |
Loads JPA components
only (repository layer) |
|
@MockBean |
Adds mock of a bean
to Spring context |
|
@TestConfiguration |
Custom configuration
class for tests |
|
Runner |
Interface |
Purpose |
Method to Implement |
Parameter Type |
Use Case |
|
CommandLineRunner |
org.springframework.boot. CommandLineRunner |
Run code after Spring Boot application starts |
run(String... args) |
Raw command-line arguments |
Simple use cases, quick startup scripts |
|
ApplicationRunner |
org.springframework.boot. ApplicationRunner |
Run code after app starts (with structured access to args) |
run( ApplicationArguments args) |
Parsed args with option access |
More control over startup args and options |
Spring Boot provides two main interfaces to run logic after the application context is initialized.
ü CommandLineRunner
Executes after the application context is loaded and
receives the command-line arguments.
ü ApplicationRunner
Similar to CommandLineRunner, but provides access to application arguments in a more structured way.
You can have multiple runners, and you can order them with @Order(1) or implement Ordered.
SpringBoot application invokes from the main() method and main() method is responsible to invoke the run() method
Run() method performs the activities like
1. Stopwatch counters
2. Prepares Environment
3. Print Banner
4. Start the IOC container
5. Refresh the context
6. Trigger runners
7. And return application context reference (Spring IOC).
|
Step |
Component/Code |
Description |
|
1 |
public static void
main(String[] args) |
Entry point of the
Spring Boot application (Java main method) |
|
2 |
SpringApplication.run() |
Boots up the Spring
application context and starts the embedded server |
|
3 |
@SpringBootApplication |
Convenience
annotation for @Configuration + @EnableAutoConfiguration + @ComponentScan |
|
4 |
Auto-configuration (@EnableAutoConfiguration) |
Spring Boot
automatically configures beans based on classpath and properties |
|
5 |
Component Scan (@ComponentScan) |
Detects and
registers @Component, @Service, @Repository, @Controller |
|
6 |
Application
Context is initialized |
All beans are
instantiated, dependencies injected |
|
7 |
CommandLineRunner /
ApplicationRunner |
Executes logic right
after application context is loaded |
|
8 |
Embedded Server
Starts (e.g., Tomcat) |
Starts embedded
servlet container and listens on the configured port |
1. Compostion
2. Factory Pattern
3. JNDI Registry
4. Inheritence
5. IOC Dependency lookup/pull and dependency injection/Push
Dependency lookup: It is an approach where we can get the resource after demand
Depedency Injection: IOC/DI describes the situation where one object uses a second object to provide a particular capacity.
Instead of you asking for dependencies, Spring pushes them into your classes. This is the "Inversion of Control" (IoC) concept
Constructor Injection when object must be created with all it’s dependencies.
Setter Injection: Use Setter Injection when the number of dependencies is large or when some of them are optional.
In field injection, Spring injects dependencies directly into class variables (fields), typically marked with @Autowired
Creating singleton beans in Spring Boot is quite straightforward because Spring beans are singleton by default. This means that when you define a bean in a Spring Boot application, Spring will create only one instance of that bean and reuse it wherever it's injected.
1. Using @Component (Default Singleton)
2. Using @Bean in a @Configuration Class
3. Explicitly Declaring Singleton Scope (Optional)
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class MySingletonService {
// Same as before
}
In Spring Boot, mutable state refers to data that can be changed during the application's runtime—like in-memory counters, caches, or user sessions
1. Using Singleton Beans with Mutable Fields
2. Using @Scope("prototype") or Request/Session Scopes (if needed)
3. Using ConcurrentHashMap or Similar for In-Memory Storage
4. Use @Scope("session") to Maintain User-Specific Mutable State
Spring Boot automatically manages the session via cookies (usually JSESSIONID).
As long as the session is active, the state is maintained for that user.
When the session expires or the browser is closed, the state is lost.
In Spring Boot, you handle exceptions centrally using the @ControllerAdvice annotation along with @ExceptionHandler. This allows you to define global exception handling logic, keeping your controllers clean and consistent.
Spring Boot Actuator provides production-ready features to help monitor and manage your application. It exposes various endpoints to get internal insights like health, metrics, environment properties, etc.
|
Actuator Endpoint |
URL Path |
Description |
|
health |
/actuator/health |
Shows application health status (UP/DOWN) |
|
info |
/actuator/info |
Displays arbitrary application info (from application.properties) |
|
metrics |
/actuator/metrics |
Shows metrics like JVM memory, CPU usage, etc. |
|
env |
/actuator/env |
Displays all environment properties |
|
beans |
/actuator/beans |
Lists all Spring beans in the application context |
|
mappings |
/actuator/mappings |
Shows all @RequestMapping paths |
|
loggers |
/actuator/loggers |
View and modify logger levels at runtime |
|
threaddump |
/actuator/threaddump |
Shows a thread dump from the JVM |
|
httptrace |
/actuator/httptrace |
Displays recent HTTP request/response trace (requires enabling
explicitly) |
|
auditevents |
/actuator/auditevents |
Displays audit events (e.g., login success/failures) |
|
shutdown |
/actuator/shutdown |
Gracefully shuts down the application (must be enabled explicitly) |
|
caches |
/actuator/caches |
Shows available caches and statistics |
|
scheduledtasks |
/actuator/scheduledtasks |
Shows scheduled tasks in the application |
|
startup |
/actuator/startup |
Displays startup steps and timing (Spring Boot 3.x+) |
|
Property |
Purpose |
|
management.endpoints.web.exposure.include=* |
Enables all actuator
endpoints |
|
management.endpoint.shutdown.enabled=true |
Enables the shutdown
endpoint |
|
management.endpoint.health.show-details=always |
Shows detailed
health info |
|
Metric Category |
Examples (Metric Names) |
Description |
|
JVM Metrics |
jvm.memory.used, jvm.threads.live |
Monitors heap, non-heap memory, GC, threads |
|
System Metrics |
system.cpu.usage, system.load.average.1m |
Tracks CPU and system load |
|
Process Metrics |
process.uptime, process.cpu.usage |
Uptime, CPU time used by the JVM |
|
HTTP Metrics |
http.server.requests |
Tracks HTTP request count, status, response times |
|
Datasource Metrics |
hikaricp.connections, jdbc.connections.active |
Monitors database connection pools |
|
Cache Metrics |
cache.gets, cache.puts, cache.evictions |
Tracks cache usage and hit/miss stats |
|
Logback Metrics |
logback.events |
Tracks log events (info, error, warn) |
|
Custom Metrics |
Custom via @Timed, MeterRegistry.counter() |
Developers can define custom metrics |
|
Step |
Configuration |
|
Add dependency |
spring-boot-starter-actuator +
micrometer-registry-prometheus |
|
Enable endpoint in application.properties |
management.endpoints.web.exposure.include=prometheus |
|
Access metrics at |
http://localhost:8080/actuator/prometheus |
|
Property |
Description |
|
management.metrics.enable.* |
Enable/disable specific metric categories |
|
management.endpoint.metrics.enabled=true |
Enable the /actuator/metrics endpoint |
|
management.metrics.distribution.percentiles |
Configure custom percentiles for timers |
|
Starter |
Usage |
Category |
|
spring-boot-starter |
Core starter, includes
auto-configuration, logging, and YAML support. |
Core |
|
spring-boot-starter-web |
Builds web, RESTful
applications using Spring MVC. Uses Tomcat as default embedded container. |
Web |
|
spring-boot-starter-data-jpa |
Simplifies JPA-based
database access. Used with Hibernate as the default JPA provider. |
Data Access |
|
spring-boot-starter-security |
Adds Spring Security for
authentication and authorization. |
Security |
|
spring-boot-starter-test |
Adds testing libraries
like JUnit, Hamcrest, Mockito, and Spring Test. |
Testing |
|
spring-boot-starter-thymeleaf |
Integrates Thymeleaf
template engine for server-side rendering of HTML. |
Template Engines |
|
spring-boot-starter-actuator |
Adds production-ready
features like health checks, metrics, and monitoring. |
Monitoring |
|
spring-boot-starter-validation |
Supports Java Bean
Validation (JSR-380) with Hibernate Validator. |
Validation |
|
spring-boot-starter-data-mongodb |
Simplifies MongoDB access
with Spring Data MongoDB. |
Data Access |
|
spring-boot-starter-batch |
Supports Spring Batch for
batch processing and ETL applications. |
Batch Processing |
|
spring-boot-starter-amqp |
Enables AMQP messaging
with RabbitMQ. |
Messaging |
|
spring-boot-starter-cache |
Adds abstraction support
for caching. |
Caching |
|
spring-boot-starter-mail |
Provides JavaMail support
for sending emails. |
Email |
|
spring-boot-starter-quartz |
Integrates Quartz
Scheduler for scheduling tasks. |
Scheduling |
|
spring-boot-starter-aop |
Adds Aspect-Oriented
Programming support using Spring AOP and AspectJ. |
AOP |
|
spring-boot-starter-data-redis |
Enables Spring Data Redis
for Redis key-value store support. |
Data Access |
|
spring-boot-starter-oauth2-client |
Supports OAuth2-based
Single Sign-On and client applications. |
Security |
|
spring-boot-starter-graphql |
Supports building GraphQL
APIs. |
API Development |
|
spring-boot-starter-websocket |
Adds WebSocket support
for real-time bi-directional communication. |
WebSocket |
|
spring-boot-starter-jdbc |
Simplifies traditional
JDBC database access. |
Data Access |
|
spring-boot-starter-integration |
Supports Spring
Integration for building messaging-based applications. |
Integration |
|
spring-boot-starter-freemarker |
Adds support for
FreeMarker template engine. |
Template Engines |
|
spring-boot-starter-mustache |
Adds support for Mustache
template engine. |
Template Engines |
|
spring-cloud-starter-circuitbreaker-resilience4j |
Provides Circuit Breaker
support using Resilience4j library. |
Cloud Resilience |
|
spring-cloud-starter-gateway |
Enables building API
gateways with routing, load balancing, and filtering using Spring Cloud
Gateway. |
Cloud API Gateway |
|
spring-kafka |
Supports Apache Kafka
integration for event-driven messaging applications. |
Messaging |
|
spring-boot-starter-activemq |
Provides support for Java
Message Service (JMS) API using ActiveMQ as the message broker. |
Messaging |
|
spring-boot-starter-webflux |
Builds reactive web
applications using Spring WebFlux with support for non-blocking APIs,
Reactor, and Netty server. |
Reactive Web |
ü
Spring
Boot (for services)
ü
API
Gateway (central entry point)
ü
Circuit
Breaker (for fault tolerance)
ü
JWT
Authentication (secure the APIs)
ü
PostgreSQL (database per service)
Each microservice handles its own domain, has its own database, and communicates through HTTP (REST) or sometimes Messaging (Kafka/RabbitMQ).
(A)
User Request
ü A client (browser/app) makes a request with
credentials (/login).
(B)
API Gateway Routing
ü Request first hits the API Gateway.
ü Gateway routes /auth/** calls to the Authentication
Service.
(C)
Authentication Service
ü Auth Service validates credentials against the
database.
ü If valid, it generates a JWT token (with
username/roles/expiry).
JWT = base64(header) +
base64(payload) + signature
ü It sends back the JWT token to the
client.
(D)
Subsequent Requests with JWT
ü
Now, for
any protected API (/user/**, /order/**):
v Client sends JWT token in Authorization
header.
v API Gateway can have a JWT filter to verify
the token before forwarding.
Example header:
Authorization: Bearer
<your_jwt_token_here>
(E)
Gateway forwards request
ü
API
Gateway checks routing rules and forwards to the correct microservice.
POST /user/create → User-Service
GET /order/history → Order-Service
(F)
Microservice verifies JWT again (optional)
ü
Microservice
may revalidate the token and extract user info from JWT for
authorization.
(G)
Business Logic + PostgreSQL
ü
Service
handles the request, interacts with its PostgreSQL database (using
JPA/Hibernate).
User user =
userRepository.findById(userId);
(H)
Circuit Breaker in Action
ü
If one
service (like Order-Service) goes down, the API Gateway (or the client
microservice) uses a Circuit Breaker to:
v Detect failure
v Open the circuit (stop requests temporarily)
v Fallback to default response
Resilience4j
example:
@CircuitBreaker(name =
"orderService", fallbackMethod = "orderFallback")
public Order
getOrder(String orderId) { ... }
If getOrder() fails,
orderFallback() will be triggered.
Let's
say:
ü
You have
an E-commerce app.
ü
User logs
in via /auth/login, gets a JWT.
ü
User
places an order via /order/create.
ü
Order-Service
talks to Order-DB.
ü
If Order-Service
is down, Circuit Breaker gives "Order Service is temporarily
unavailable" instead of crashing the app.
(using
@Transactional): Spring manages the transaction boundaries for you, calling
COMMIT or ROLLBACK based on success or exception.
ü
✅ Easier to work with in complex business
workflows.
ü
✅ Integrates well with services, repositories,
multiple DBs, and external systems.
ü
✅ Easier to maintain, test, and debug.
ü
❌ Slightly more overhead than pure DB
transactions.
Handling global exceptions in Spring Boot is super important for clean, maintainable, and user-friendly error management. The best way to handle global exceptions is through @ControllerAdvice. It provides a centralized way of handling exceptions across your whole application.
How to Handle Global Exceptions in Spring Boot
Create a Global Exception Handler with @ControllerAdvice
ü @ControllerAdvice is used to handle exceptions
in a centralized way, across all controllers.
ü It can be used to handle specific exceptions or
general exceptions for your entire application.
|
Component |
Technology /
Pattern |
Purpose |
|
Service Layer |
Spring Boot
Microservices |
Independent, loosely
coupled services for business domains |
|
API Gateway |
Spring Cloud Gateway
/ Zuul |
Single entry point,
routing, security, and rate-limiting |
|
Service Discovery |
Eureka / Consul |
Dynamic service
registration and discovery |
|
Load Balancer |
Ribbon (legacy),
Spring Cloud LoadBalancer, external (e.g. NGINX) |
Distributes requests
across instances |
|
Configuration |
Spring Cloud Config
Server / Vault |
Centralized and
dynamic configuration management |
|
Database Layer |
Polyglot Persistence
(MySQL, MongoDB, PostgreSQL) |
Each service has its
own DB (Database per service pattern) |
|
Communication |
REST (Feign),
Messaging (RabbitMQ/Kafka) |
Sync (Feign) and
Async (Messaging) communication |
|
Security |
OAuth2 / JWT /
Spring Security |
Centralized
authentication and authorization |
|
Observability |
Spring Boot
Actuator, Micrometer + Prometheus + Grafana |
Metrics, health
checks, and custom monitoring |
|
Logging |
ELK (Elasticsearch,
Logstash, Kibana) / EFK (Fluentd) |
Centralized logging
and search |
|
Tracing |
Sleuth + Zipkin /
Jaeger |
Distributed tracing |
|
Containerization |
Docker |
Packaged and
portable deployment |
|
Orchestration |
Kubernetes (AKS,
EKS, GKE) |
Automated
deployment, scaling, and management |
|
CI/CD |
GitHub Actions /
Jenkins / Azure DevOps |
Automated build,
test, and deployment pipelines |
|
Design Element |
Approach |
|
Bounded Context |
Each service aligns with a single business domain (e.g., User, Order,
Payment) |
|
Loose Coupling |
Services interact via REST APIs or messaging queues |
|
High Cohesion |
Encapsulate business logic within a single service |
|
Resilience |
Circuit Breakers (Resilience4j), retries, timeouts |
|
Scalability |
Stateless services + Kubernetes HPA |
|
Layer |
Technology |
|
API Gateway |
Spring Cloud Gateway |
|
Service Discovery |
Netflix Eureka |
|
Inter-Service Comm. |
Feign, Kafka |
|
Configuration |
Spring Cloud Config |
|
Authentication |
Keycloak / OAuth2 / JWT |
|
Monitoring |
Prometheus + Grafana |
|
Tracing |
Sleuth + Zipkin |
|
Logging |
Logback +
Elasticsearch/Kibana |
|
Deployment |
Docker + Kubernetes (AKS) |
+---------------------+
| Client UI |
+---------------------+
|
▼
+---------------------+
|
API Gateway |
+---------------------+
|
+------------+------------+
| | |
▼ ▼ ▼
+---------+
+----------+ +----------+
|
Order | |
User | | Payment
| ← Spring Boot Services
+---------+
+----------+ +----------+
| | |
+---------+
+----------+ +----------+
|MySQL DB |
|MongoDB | |Postgres
|
+---------+
+----------+ +----------+
(All services registered in
Eureka)
Scalability
Features Implemented
|
Feature |
Details |
|
Horizontal Scaling |
Services are stateless and
deployed as replicas in Kubernetes |
|
Central Config |
Spring Cloud Config Server
enables dynamic reloading via Actuator |
|
Health Monitoring |
/actuator/health used by
Kubernetes for liveness/readiness checks |
|
Resilience |
Retry and circuit breaker
patterns via Resilience4j |
|
Asynchronous Messaging |
Kafka used for
non-blocking inter-service communication (e.g., order events) |
|
JWT Security |
Auth tokens are validated
at the API Gateway level |
|
Autoscaling |
HPA scales pods based on
CPU/memory/requests per second |
ü Avoid
shared databases across
microservices.
ü Use DTOs and API contracts to decouple
services.
ü Ensure backward compatibility for APIs.
ü Use rate limiting and throttling at the
gateway.
ü Enable caching for frequently accessed data
(e.g., Redis).
ü Isolate faults using bulkheads and circuit
breakers.
When handling service discovery and communication between microservices, especially in a Spring Boot microservice architecture, you typically use a combination of tools like Eureka, Feign, and RestTemplate.
1. Service Discovery (Eureka)
Eureka is a service
registry from Netflix used to register and discover services in a microservices
architecture.
ü
Eureka
Server acts as a registry
where all client services register themselves.
ü
Eureka
Client registers the service
and queries other services via Eureka.
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
2.
Service
Communication Options
A.
Feign Client (Declarative REST Client)
ü
Simplifies
HTTP calls with a declarative interface.
ü
Automatically
integrates with Eureka for service discovery.
Use when: You want
cleaner, readable code and tighter Spring Cloud integration.
@FeignClient(name
= "order-service")
public
interface OrderClient {
@GetMapping("/orders/{id}")
Order
getOrderById(@PathVariable("id") Long id);
}
@EnableFeignClients
@SpringBootApplication
public
class Application { }
RestTemplate
Use when: You want full control over the HTTP request or need to integrate with
external APIs.
@Autowired
private
RestTemplate restTemplate;
public
Order getOrderById(Long id) {
return
restTemplate.getForObject("http://order-service/orders/" + id,
Order.class);
}
@Bean
@LoadBalanced
// Enables service name resolution via Eureka
public
RestTemplate restTemplate() {
return new RestTemplate();
}
Spring Cloud Config provides centralized configuration management for distributed microservices. It allows you to externalize configuration properties from your application code and manage them in a central Git repository (or Vault, JDBC, etc.).
Why use Spring Cloud Config?
|
Problem |
Solution with Spring Cloud Config |
|
Duplication of configs across services |
Centralized config in a single place (e.g., Git) |
|
Manual config updates |
Dynamic refresh using @RefreshScope and actuator/refresh |
|
Multiple environments (dev, qa, prod) |
Profile-specific YAMLs like application-prod.yml |
|
Secrets and sensitive values |
Support for integration with Vault, KMS, etc. |
Summary
|
Aspect |
Spring Cloud Config Benefits |
|
Centralized management |
Yes (via Git, Vault, etc.) |
|
Environment segregation |
Yes (via profiles) |
|
Dynamic reload |
Yes (@RefreshScope, Spring Cloud Bus) |
|
Secret management |
Yes (Vault integration) |
|
Production safe? |
Yes, when using secure backends + Bus + refresh |
Securing microservices is critical in distributed architectures. You typically secure them using Spring Security, OAuth2, and JWT. Here's a structured breakdown of how to secure microservices in a modern Spring Boot setup:
|
Security Concern |
Solution |
|
Identity verification |
OAuth2 / OpenID Connect |
|
Token-based auth |
JWT (JSON Web Tokens) |
|
Central auth management |
Authorization Server (e.g., Keycloak, Auth0) |
|
Service-to-service auth |
Propagate JWT or use Mutual TLS |
A. Spring Security
B. OAuth2 / OpenID Connect
C. JWT (JSON Web Token)
ü Client logs in via Authorization Server (Keycloak, Auth0, Okta, etc.)
ü Server issues an Access Token (JWT).
ü Client includes JWT in the Authorization header
for every request:
Authorization: Bearer <token>
ü Validates the token signature and expiry.
ü Extracts claims for role-based access control.
Versioning REST APIs is critical for maintaining backward compatibility while allowing continuous evolution of your services. Here's a structured approach to REST API versioning:
|
Purpose |
Benefit |
|
Avoid breaking changes |
Clients using old versions keep working |
|
Allow iterative improvements |
New features added in new versions |
|
Support multiple client versions |
Mobile apps, third-party consumers |
|
Purpose |
Benefit |
|
Avoid breaking changes |
Clients using old versions keep working |
|
Allow iterative improvements |
New features added in new versions |
|
Support multiple client versions |
Mobile apps, third-party consumers |
|
Best Practice |
Why It Matters |
|
Use semantic versioning (v1, v2) |
Clear evolution of API |
|
Keep versions backward compatible |
Avoid breaking existing clients |
|
Deprecate old versions gradually |
Communicate EOL to clients |
|
Document version changes clearly |
Use Swagger/OpenAPI per version |
|
Use consistent versioning strategy |
Across all microservices |
Ensuring high availability (HA) and fault tolerance is critical for resilient, production-grade systems
Design for Failure
ü Assume components will fail at some
point — hardware, network, software bugs.
ü Build systems that gracefully degrade
rather than catastrophically crash.
Redundancy & Replication
ü Deploy multiple instances of services behind load
balancers.
ü Use replicated databases or distributed
data stores (e.g., master-slave, multi-master).
ü Data replication ensures no single point of
failure.
Failover Mechanisms
ü Use automated failover for services and
databases.
ü Health checks and heartbeats detect failures;
traffic routed away from unhealthy nodes.
ü Example: Kubernetes readiness/liveness probes +
service mesh retries.
Stateless Services
ü Design services to be stateless wherever
possible.
ü Store state externally (databases, caches,
distributed storage).
ü Makes horizontal scaling and failover simpler.
Graceful Degradation & Circuit Breakers
ü Implement circuit breakers (e.g.,
Resilience4j, Hystrix) to avoid cascading failures.
ü Provide fallback methods or degraded service
responses if downstream systems fail.
Load Balancing & Auto-Scaling
ü
Use load
balancers (AWS ALB, NGINX, Envoy) to distribute traffic evenly.
ü
Set up auto-scaling
to handle spikes and failures by launching/removing instances dynamically.
Distributed Data Consistency
ü Use databases/configurations that support HA
(e.g., distributed consensus protocols like Raft, Paxos).
ü Choose appropriate consistency models
(strong vs eventual) based on application needs.
Data Backup & Recovery
ü Regular backups of data and
configurations.
ü Tested recovery plans in place for disaster
scenarios.
Monitoring, Alerting & Incident Response
ü Comprehensive monitoring (metrics, logs,
traces).
ü Alerting on failures and thresholds.
ü Runbooks and automation for incident
management.
Chaos Engineering
ü Intentionally inject failures in a controlled
manner (e.g., Netflix Chaos Monkey).
ü Identify weaknesses and improve system
resilience proactively.
Summary Table:
|
Strategy |
Purpose |
Example Tools / Techniques |
|
Redundancy & Replication |
Eliminate SPOF |
Kubernetes, Multi-AZ DB replicas |
|
Failover |
Auto switch on failure |
Kubernetes probes, DNS failover |
|
Stateless Design |
Easy scaling & recovery |
External session stores |
|
Circuit Breakers |
Avoid cascading failures |
Resilience4j, Hystrix |
|
Load Balancing & Auto-Scaling |
Handle load and failures |
AWS ALB, Kubernetes HPA |
|
Monitoring & Alerting |
Early detection & response |
Prometheus, Grafana, PagerDuty |
|
Chaos Engineering |
Test fault tolerance |
Chaos Monkey, Gremlin |
|
Component |
Role |
|
API Gateway |
Single entry point for all client requests, routing, authentication,
rate limiting, and request aggregation. |
|
Service Mesh |
Manages inter-service communication with features like service
discovery, load balancing, retries, circuit breaking, and security. |
|
Microservices |
Independently deployable services implementing business capabilities,
communicating over the network. |
|
Observability |
Monitoring, logging, tracing, and alerting across all services to gain
insight and detect issues. |
You can specify a different port for Actuator endpoints by setting the management.server.port property in your application.properties or application.yml.
server.port=8080 # Application runs on port 8080
management.server.port=8081 # Actuator runs on port 8081
management.endpoints.web.exposure.include=* # Expose all actuator endpoints
Instead of fully overriding /health, you typically contribute custom health indicators:
@Component
public class MyCustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
}
Fully Override the /health Endpoint (Not Recommended)
Exclude the default Actuator /health
management.endpoints.web.exposure.exclude=health
@RestController
public class CustomHealthController {
@GetMapping("/health")
public ResponseEntity<Map<String, Object>> customHealth() {
Map<String, Object> status = new HashMap<>();
status.put("status", "CUSTOM_HEALTH_OK");
status.put("timestamp", Instant.now());
return ResponseEntity.ok(status);
}
}
ü
Break monolith into
domain-driven bounded contexts.
ü
Use Spring Boot for each
service.
ü
Communication via REST,
gRPC, or messaging (Kafka, RabbitMQ).
ü
Service discovery with
Eureka or Consul.
ü
Load balancing with Spring
Cloud Gateway + Ribbon.
ü
Centralized config (Spring
Cloud Config), monitoring (Prometheus + Grafana).
ü
Security: OAuth2/JWT with
Spring Security.
Bounded Context is a key concept in Domain-Driven Design (DDD). It helps you clearly define the boundaries within which a specific domain model applies — especially important in large-scale, enterprise, or microservices-based systems.
Reactive programming is
an asynchronous programming paradigm that focuses on non-blocking, event-driven
data processing with backpressure handling.
It’s useful when:
ü
You need
to handle a large number of concurrent users.
ü
The
application is I/O-bound (e.g., waiting for DB, APIs).
ü
You want
to optimize resource utilization (threads, memory).
Spring Boot Reactive
Spring Boot uses the Spring WebFlux module to support reactive
programming using:
ü
Mono<T>
– Represents 0 or 1 result
ü
Flux<T>
– Represents 0 to N results (a stream)
Built on Project Reactor, a reactive library for Java.
When to Use It
ü Your system is event-driven or message-based.
ü You need high concurrency with limited
hardware.
ü You integrate with non-blocking downstream
systems.
@GetMapping
public Flux<Employee> getAll() {
return service.getAll();
}
@GetMapping("/{id}")
public Mono<Employee> get(@PathVariable String id) {
return service.getById(id);
}
@PostMapping
public Mono<Employee> create(@RequestBody Employee emp) {
return service.save(emp);
}
To handle large files in Azure, we store them in Azure Blob. We split the file logically and use Service Bus to distribute chunks to Spring Boot instances. The app is containerized and deployed to AKS, and we scale it horizontally using HPA based on CPU or queue depth. This enables dynamic scaling and efficient processing.
1. Understand the Query
ü
What data
is being requested?
ü
How frequently is it run?
ü
How big are the tables involved?
2.
Use EXPLAIN / EXPLAIN ANALYZE
Use the database’s query plan tool to see how the query is executed.
ü
Which
indexes are being used
ü
If full
table scans are happening
ü
Estimated
rows being scanned
3. Optimize the SELECT Clause
4.
Add or Improve Indexes
Create indexes on columns used in WHERE, JOIN, GROUP BY, or ORDER BY
5.
Rewrite the Query
ü
Sometimes
breaking a complex query into smaller steps (e.g., with CTEs or temp tables)
helps.
ü
Also:
ü
Replace
subqueries with joins (or vice versa), depending on which performs better.
ü
Use EXISTS
instead of IN when appropriate.
6.
Use Proper Joins
Make sure joins use indexed keys and are selective:
7.
Limit Result Set
8.
Analyze and Vacuum
(PostgreSQL-specific)
9.
Consider Materialized Views or
Caching
10. Database-Specific Tools
Each
DB has tools:
ü MySQL: EXPLAIN, SHOW PROFILE
ü PostgreSQL: EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements
ü SQL Server: Execution Plans, Query Store
ü Oracle: SQL Trace, TKPROF
An index in a database is a data structure that improves the speed of data retrieval operations on a table at the cost of additional storage and write time
Why Use Indexes?
ü Speed up SELECT queries.
ü Improve JOIN, WHERE, ORDER BY,
GROUP BY operations.
ü Reduce full table scans.
ü At a cost of:
v
Slower
write operations.
v
Increased
storage usage.
Types of Indexes in PostgreSQL
|
Index Type |
Description |
Use Case |
|
B-Tree Index |
Default index type. Balanced tree structure. Supports equality and
range queries. |
=, <, >, BETWEEN, ORDER BY. |
|
Hash Index |
Index based on hash values. Supports equality (=) lookups only. |
Exact match queries, e.g., WHERE user_id = 42. |
|
GIN (Generalized Inverted Index) |
Efficient for indexing array values, JSONB, and full-text search. |
Full-text search or JSONB fields like tags @> ['sql']. |
|
GiST (Generalized Search Tree) |
Supports custom strategies for complex data types. |
Geometric data, ranges, full-text, and fuzzy search. |
|
SP-GiST (Space-Partitioned GiST) |
Better suited for non-balanced trees and partitioned data. |
Hierarchical or spatial data (e.g., quadtrees). |
|
BRIN (Block Range Index) |
Summarizes ranges of data blocks. Compact and efficient for large
tables. |
Very large tables with naturally sorted data. |
|
Expression Index |
Indexes based on the result of an expression. |
CREATE INDEX ON users (lower(email)). |
|
Partial Index |
Index only a subset of rows matching a condition. |
WHERE is_active = true. Reduces size, speeds up queries. |
|
Unique Index |
Enforces uniqueness on one or more columns. |
email or username must be unique. |
|
Composite Index |
Index on multiple columns. Order matters. |
CREATE INDEX ON orders (user_id, created_at);. |
|
Covering Index (INCLUDE) |
Stores additional columns in the index to avoid lookups. (PostgreSQL
11+) |
CREATE INDEX ON users (id) INCLUDE (email, name); |
13.1 Interview Question
|
Question |
Sample Answer |
|
When do you use a
clustered index? |
When you frequently
query data by primary key or a column that requires sorting. |
|
Can a table have
multiple clustered indexes? |
No, only one
clustered index is allowed per table. |
|
What about
non-clustered indexes? |
You can create multiple
non-clustered indexes on different columns to speed up searches. |
In databases, cursors and refcursors are tools used in procedural SQL (like PL/pgSQL in PostgreSQL or PL/SQL in Oracle) to work with query results row-by-row, especially inside stored procedures or functions.
A cursor is a database object used to retrieve a set of rows returned by a query and process them one at a time. It's useful when you need to perform operations on each row individually.
How it works:
ü
Declare
the cursor (based on a query).
ü
Open the
cursor (execute the query).
ü
Fetch rows
from the cursor (one or more at a time).
ü
Close the
cursor when done.
DECLARE
my_cursor CURSOR FOR SELECT id, name FROM
users;
user_record RECORD;
BEGIN
OPEN my_cursor;
LOOP
FETCH my_cursor INTO user_record;
EXIT WHEN NOT FOUND;
-- Do something with user_record
END LOOP;
CLOSE my_cursor;
END;
A refcursor is a cursor variable—a pointer or reference to a result set. It's more dynamic and flexible than a regular cursor and is often used when you want to return a result set from a function or procedure.
Why use refcursors?
ü
You can
pass them around as variables.
ü
You can
return them from functions.
ü
Great for
client applications that need to fetch large or variable result sets.
Example returning a refcursor:
CREATE
OR REPLACE FUNCTION get_users()
RETURNS
refcursor AS $$
DECLARE
ref refcursor;
BEGIN
OPEN ref FOR SELECT * FROM users;
RETURN ref;
END;
$$
LANGUAGE plpgsql;
A trigger is a special kind of stored procedure that automatically runs (is "triggered") in response to certain events on a table or view.
When Do Triggers Fire?
Triggers
can be fired:
Use Cases for Triggers
ü
Logging/auditing
changes
ü
Validating
or enforcing complex rules
ü
Automatically
updating timestamps
ü
Denying
certain operations
ü
Cascading
updates/deletes (in custom ways)
IN Parameter
Input only: Passes a value into the procedure.
Value is read-only inside the procedure.
Default type if nothing is specified.
Cannot be modified within the procedure (any changes won't reflect outside).
OUT Parameter
Used to return a value from the procedure to the caller.
Cannot be used to pass input into the procedure.
Acts like a return variable.
INOUT Parameter
Works both ways:
Passes a value into the procedure.
Allows the procedure to modify it and return the updated value.
Raise
an exception in stored procedure
RAISE EXCEPTION 'Balance cannot be negative';
PostgreSQL lets you use RAISE NOTICE, RAISE WARNING, or RAISE EXCEPTION
How
to handle errors/exception in stored procedure
BEGIN
-- normal code
EXCEPTION
WHEN <exception_name> THEN
-- handle the exception
WHEN OTHERS THEN
-- handle any other exception
END;
13.5.1 Different types of database types
To execute a stored procedure from Java/Spring Boot/JPA, you have multiple ways to achieve this depending on the JPA provider (e.g., Hibernate) and the type of procedure (i.e., IN, OUT, or INOUT parameters).
1. Select dept_id, max(sal) from employee group by dept_id;
2. Select * from emp where manager_id is null;
3. Select a.name as employee,b.name as manager from emp a left outer join
Emp b on a.manager_id=b.manager_id;
4. Select dept_id,count(*) from emp group by email having count(*) >1;
5. Select emp_id, salary, rank() over (order by sal desc) as salary_rank from emp;
6. Update-time< now – interval 30 day;
A CTE (Common Table Expression) in databases is a temporary result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. It's defined using the WITH keyword and is often used to improve readability and structure of complex queries, especially those involving recursion or subqueries.
SELECT ...
)
SELECT * FROM cte_name;
SELECT ...
),
cte2 AS (
SELECT ...
)
SELECT * FROM cte2;
Benefits of
Using CTEs
ü Makes queries more readable and maintainable
ü Can be recursive (great for
hierarchical/tree data)
ü Allows you to reference the CTE multiple times
in the main query
Snowflake: à Snowflake is a cloud-based data warehouse platform. It provides a Software-as-a-Service (SaaS) solution that allows companies to store, process, and analyze large volumes of structured and semi-structured data.
Key Features:
ü
Built for
AWS, Azure, and GCP.
ü
Separates storage
and compute, so you can scale them independently.
ü
Automatically
scales to handle concurrency.
ü
No
performance bottlenecks with multiple users.
ü
No
indexing, tuning, or infrastructure to manage.
ü
Fully
managed by Snowflake.
ü
Securely
share data across organizations without data movement.
ü
Handles
structured data (tables) and semi-structured (JSON, Avro, Parquet).
ü
Optimized
for SQL workloads; very friendly to analysts and BI tools.
Use Cases:
ü
Business
Intelligence (BI) and reporting.
ü
Data
warehousing.
ü
Data
sharing between organizations.
ü
Real-time
analytics (to some extent).
Databricks
Databricks is a data lakehouse platform that combines the best features of data lakes and data warehouses. It’s built on top of Apache Spark and supports advanced data engineering, data science, and machine learning workflows.
Use Cases:
ü
Data
science & ML pipelines.
ü
ETL/ELT
processing.
ü
Big Data
analytics.
ü
Real-time
streaming analytics.
ü
Unified
analytics from raw to curated data.
public interface
PagingAndSortingRepository<T, ID> extends CrudRepository<T,
ID>
@NoRepositoryBean
à Annotation to exclude repository interfaces from being picked up and
thus in consequence getting an instance being created.
public interface
JpaRepository<T, ID> extends PagingAndSortingRepository<T,
ID>, QueryByExampleExecutor<T> {
CrudRepository: Provides basic CRUD (Create, Read, Update, Delete) operations
ü
Key
Methods:
Ø save(S entity)
Ø findById(ID id)
Ø findAll()
Ø deleteById(ID id)
Ø deleteAll()
Use
CrudRepository when you only need simple CRUD functionality.
JpaRepository:
ü Extends: PagingAndSortingRepository, which itself extends CrudRepository
ü Purpose: Adds JPA-specific features + pagination and sorting
capabilities.
ü Use JpaRepository when you need advanced JPA operations, pagination,
or batch processing.
JpaRepository
→ PagingAndSortingRepository → CrudRepository
TypedQuery<Campaign>
typedQuery = entityManager.createQuery(query);
final int pageSize =
(searchDto.getPageSize() > 0 ? searchDto.getPageSize() : Integer.MAX_VALUE);
final int pageNumber =
Math.max(searchDto.getPageNumber(), 1);
typedQuery.setFirstResult((pageNumber - 1)
* pageSize);
typedQuery.setMaxResults(pageSize);
countQuery.select(criteriaBuilder.count(fromCount));
Long totalElements =
entityManager.createQuery(countQuery).getSingleResult();
final List<Campaign> list =
typedQuery.getResultList();
final List<CampaignSearchOutDto>
result = new ArrayList<>();
if (list != null) {
for (Campaign campaign : list) {
result.add(buildDto(campaign));
}
}
int availablePages =
totalElements.intValue() / pageSize + (totalElements.intValue() % pageSize != 0
? 1 : 0);
Integer nextPage = pageNumber + 1 ==
availablePages ? null : pageNumber + 1;
Integer nextItems = nextPage == null ? 0 :
totalElements.intValue() - (pageSize * (pageNumber + 1));
Integer previousPage = availablePages == 1
? null : pageNumber - 1;
Integer previousItems = previousPage ==
null ? 0 : pageSize * pageNumber;
logSpentTime("searchCampaignsByPaginationFilterV2",
startTime);
LOGGER.debug(LOG2_, result, searchDto);
return new
PaginatedOutDto<CampaignSearchOutDto>(totalElements.intValue(),
availablePages, nextPage, previousPage, nextItems, previousItems,
availablePages - 1,
result);
A
transaction is a sequence of one or more operations that must all be
completed successfully; otherwise, none of them should be applied. It follows
the ACID principles:
ü
Atomicity: All or nothing
ü
Consistency: Valid state before and after
ü
Isolation: Transactions don’t interfere
ü
Durability: Once committed, it stays
Where to Maintain Transactions?
Best Practice: Service Layer in Spring Boot
Why at the service layer?
ü
Business
logic usually lives in the service layer, which coordinates multiple
DAOs or repositories.
ü
Keeping
transaction boundaries in services provides modularity and reusability
of data access code.
ü
Allows
control over transaction scope (begin/commit/rollback) where it
logically makes sense.
Backed by: Relational Database (like MySQL/PostgreSQL)
ü
Relational
databases natively support ACID transactions.
ü
Use
database's transaction capabilities through Spring's abstraction.
Propagation (Spring Transaction Propagation Behavior)
Propagation
defines how transaction boundaries behave when a method is called within an
existing transaction.
|
Propagation Type |
Description |
|
REQUIRED |
Joins existing transaction, or creates a new one if none exists (default). |
|
REQUIRES_NEW |
Suspends current transaction, starts a new one. |
|
SUPPORTS |
Joins existing if present, else non-transactional. |
|
NOT_SUPPORTED |
Suspends any existing transaction, runs non-transactionally. |
|
MANDATORY |
Must be called within an existing transaction, else exception. |
|
NEVER |
Must be called outside a transaction, else exception. |
|
NESTED |
Runs in a nested transaction (uses savepoints), if a
transaction exists. |
Isolation Levels (Database Transaction Isolation)
Isolation
controls how visible the changes made in one transaction are to others,
affecting data consistency and concurrency.
|
Isolation Level |
Description |
Issues Prevented |
|
READ_UNCOMMITTED |
Allows dirty reads. Least isolation. |
None |
|
READ_COMMITTED |
Prevents dirty reads. Default in many DBs. |
Dirty reads |
|
REPEATABLE_READ |
Prevents dirty and non-repeatable reads. |
Dirty, non-repeatable reads |
|
SERIALIZABLE |
Highest isolation, full ACID. |
All (dirty, non-repeatable, phantom) |
Common Mistakes to Avoid
|
Mistake |
Why it's bad |
|
Using @Transactional on private methods |
Spring AOP won’t proxy it, so transaction won't apply |
|
Putting transactions in Controller |
Violates separation of concerns, makes debugging hard |
|
Not handling exceptions |
Could result in partial commits if not handled properly |
|
Using NoSQL DBs without transaction support |
May cause data inconsistency in multi-step updates |
Maintain transactions in the service layer using @Transactional backed by a relational database. This is accurate, scalable, and aligns with both Spring's architecture and database ACID guarantees.
@Transactional is a Spring annotation used to manage transaction boundaries declaratively. It ensures that the logic inside a method runs within a database transaction, and can be committed or rolled back based on success or failure.
Defaults:
ü
Propagation: REQUIRED
ü
Isolation: DEFAULT
ü
readOnly: false
ü
rollbackFor: Only unchecked exceptions (RuntimeException
and Error)
Spring only rolls back on uncaught runtime exceptions. If you catch
and swallow the exception, the transaction won’t roll back.
To manually trigger rollback:
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
It bypasses the
proxy — transaction will not apply.
Solution: Move the method to another bean or use AspectJ weaving instead of
proxy-based AOP.
@Transactional(readOnly = true)
Used for read-only
operations, it:
ü
Can avoid
flush and dirty checks
ü
Optimizes
performance (especially in Hibernate)
ü Uses PlatformTransactionManager (like
JpaTransactionManager)
ü Auto-configured by Spring Boot if using
spring-boot-starter-data-jpa
ü Integrates with Hibernate, EntityManager,
and DataSource
Spring uses AOP proxies (JDK or CGLIB) to intercept method calls and apply transaction behavior before and after the method execution.
@Transactional(rollbackFor = { CustomBusinessException.class, IOException.class })
When a method in one service
calls a method in another service, we must be careful whether the second
method:
ü continues using the existing transaction or
ü starts a new one or
ü suspends the current one temporarily.
This behavior is controlled by the propagation setting inside @Transactional.By default, Propagation.REQUIRED is
used — meaning if a transaction exists, it will join it, else it creates a new one.