Spring Boot

Article 16: Performance & Caching in Spring Boot

By Utility Zone · 2026-01-27T18:28:44.200323

1. Introduction

As applications grow, performance becomes critical.

Without caching:

  • Same data is fetched repeatedly
  • Databases get overloaded
  • APIs become slow

Caching helps you:

  • Improve response time
  • Reduce database load
  • Scale efficiently

Spring Boot provides simple yet powerful caching support.


2. What Is Caching?

Caching means:

Storing frequently accessed data temporarily so it can be reused quickly.

Instead of:

Request → DB → Response

You get:

Request → Cache → Response

3. When Should You Use Caching?

Use caching when:

  • Data is read frequently
  • Data changes infrequently
  • Performance is critical

Avoid caching when:

  • Data changes constantly
  • Strong consistency is required

4. Enabling Caching in Spring Boot

Add dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Enable caching:

@SpringBootApplication
@EnableCaching
public class DemoApplication {
}

5. Using @Cacheable

@Service
public class UserService {

    @Cacheable("users")
    public User getUserById(Long id) {
        simulateSlowService();
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("User not found"));
    }
}

First call → slow
Next calls → fast


6. Cache Key Behavior

Default key:

  • Method parameters

Example:

getUserById(1)

Cache key = 1


7. Using @CacheEvict

When data changes, cache must be cleared.

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
    userRepository.deleteById(id);
}

8. Using @CachePut

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}

Updates cache without skipping method execution.


9. Cache Providers

Spring Boot supports multiple cache providers:

ProviderUse Case
ConcurrentMapDefault (simple)
CaffeineHigh performance
RedisDistributed cache
EhCacheLegacy

For learning: ✔ Default cache is enough

For production: ✔ Redis / Caffeine


10. Configuring Cache Provider (Example: Caffeine)

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>
spring.cache.type=caffeine

11. Common Caching Mistakes

❌ Forgetting to evict cache
❌ Caching mutable data
❌ Over-caching everything
❌ Ignoring TTL (time-to-live)


12. Best Practices

✔ Cache at service layer
✔ Keep TTL reasonable
✔ Monitor cache hits/misses
✔ Combine caching with DB indexing


13. What You Should Understand Before Moving On

You should now know:

  • Why caching improves performance
  • How @Cacheable works
  • How to evict and update cache
  • Which cache provider to choose

14. What’s Next?

➡ Article 17: Testing Spring Boot Applications

  • Unit tests
  • Integration tests
  • MockMvc & Mockito

Type Next when you’re ready.