










Hibernate Level 1 caching : ( default ) session caching. This is for the particular instance of the session
Hibernate Level 2 caching : session Factory caching. All the sessions will have same caching


What is Cache?
-> Cache is a temporary fast-access storage used to store frequently
accessed data so that repeated expensive operations can be avoided.
-> As we know that hitting each request to DB is really very cost effective
operation, so cache will reduce database load, slashing latency, and improving
application performance.
📌 Instead of hitting DB / API / Disk every
time, we return data from cache.
1️⃣
Where Do We Use Cache ? (Real-Time Examples):
🔹 User profile data
🔹 Product catalog
🔹 Configuration data
🔹 Authentication & authorization data
🔹 Search results
🔹 API responses.
2️⃣
Types of Cache :
🔹In-Memory Cache :
1. Stored inside application memory
2. Very fast
3. Data lost on restart
Examples: HashMap, Caffeine.
🔹Distributed Cache
1. Shared across multiple services
2. Highly scalable.
Examples: Redis, Memcached.
📌 Used in microservices & cloud systems
🔹Client-Side Cache
1. used in browser / mobile app.
2.Reduces server calls.
3️⃣
Cache Levels:
🟢 L1 Cache:
1.Closest to application
2.Fastest
3.Limited size
🔵 L2 Cache:
1.Shared across services
2.Slower than L1 but scalable.
4️⃣ Cache
Consistency Problem:
❌ Cache data can become stale
✔ Solution:
✅ providing TTL (Time To Live)
✅ Cache invalidation
✅ Event-based updates.
5️⃣
How Cache Works (Simple Flow):
Client → Application → Cache
↓ (miss)
Database
✔ Cache Hit →
return data
✔ Cache Miss →
fetch from DB → store in cache →
return data.
6️⃣Cache
in Spring Boot :
𝐄𝐧𝐚𝐛𝐥𝐞 𝐂𝐚𝐜𝐡𝐞:
@EnableCaching
@SpringBootApplication
public class App { }
𝐔𝐬𝐞 @𝐂𝐚𝐜𝐡𝐞𝐚𝐛𝐥𝐞 :
@Cacheable("products")
public Product getProductById(Long id) {
return productRepository.findById(id).get();
}
✔ First call →
DB
✔ Next calls →
Cache.
𝐔𝐩𝐝𝐚𝐭𝐞 𝐂𝐚𝐜𝐡𝐞:
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
𝐑𝐞𝐦𝐨𝐯𝐞 𝐂𝐚𝐜𝐡𝐞:
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
7️⃣
Cache Providers in Spring Boot:
☑️ Caffeine (in-memory).
☑️Redis (distributed – most used)
☑️Hazelcast.
📌 Redis is preferred for microservices.
8️⃣
Cache in Microservices (Real-Time)
✔ Each service uses Redis
✔ Reduces DB load
✔ Improves API latency
✔ Supports horizontal scaling.
Example:
Product Service → Redis →
Database.
