Showing posts with label Redis Caching. Show all posts
Showing posts with label Redis Caching. Show all posts

Redis Caching in Spring Boot: Complete Guide with Java 17

Redis Caching in Spring Boot: A Complete Tutorial with Java 17 Example

Learn Redis caching in Spring Boot with a complete, working Java 17 example. This guide walks through the Cache-Aside pattern, the three Spring cache annotations, a real product API using MySQL and Spring Data JPA, and the production practices that keep caching reliable under load.

Here is a scenario I have seen more than once. A product detail API takes 80ms per request. At 10,000 requests, most of them asking for the same popular products, the database connection pool starts throwing warnings. Adding a Redis cache dropped the response time to a few milliseconds for cache hits and cut database load by roughly 70%. Nothing exotic — just storing data that was already fetched in memory so the next request does not repeat the same query.

The tricky part is not adding Redis. The tricky part is knowing when to write the cache, when to invalidate it, and what to do when it fails. This tutorial walks through all three.

What you will build: a Product Management REST API that reads product data from MySQL, caches it in Redis, and keeps the cache in sync when products are updated or deleted.

What Is Redis?

Redis (Remote Dictionary Server) is an in-memory data store that supports several data structures and is commonly used for caching, messaging, and low-latency data access. Unlike a traditional relational database, Redis keeps frequently accessed data in memory, which makes reads extremely fast.

Redis supports several data structures:

Type What it stores
String Text, numbers, and serialized values
Hash Field-value pairs
List Ordered collections of values
Set Unique values
Sorted Set Values with associated scores
Stream Append-only event data

For a product API, a cache key might look like products::101. Once the key is written, Redis can return the cached value on the next request without touching MySQL.

Why Do We Need Redis Caching?

Suppose your application receives 10,000 product API requests. Many customers are asking for the same popular products. Without caching, every request may execute a database query. With caching, repeated requests are served from Redis when a valid cache entry exists.

Metric Without caching With caching
Total API requests 10,000 10,000
Cache hits 0 ~7,000
Cache misses 10,000 ~3,000
Database reads 10,000 ~3,000
Database load Higher Lower

Note: these are illustrative numbers assuming a warm cache and no expiration during the measured requests. Actual results depend on workload and hit rate.

Major Benefits of Redis

  • Low-latency access: frequently requested data is served from memory.
  • Reduced database load: repeated queries are avoided.
  • Improved scalability: the database stays free for operations that need it.
  • Shared cache: multiple Spring Boot instances can use the same Redis deployment.
  • Flexible expiration: cached data can expire automatically with TTL.

How Redis Caching Works: The Cache-Aside Pattern

The most common caching approach is called Cache-Aside. The application checks the cache first. If the data is missing, it reads from the database and stores the result in the cache.

Cache-Aside architecture with Spring Boot, Redis, and MySQL A client sends a request to Spring Boot. Spring checks Redis first. On a hit, cached data is returned. On a miss, Spring queries MySQL and writes the result to Redis. Client / API Spring Boot Service + Cache Manager Redis Cache Cache Hit / Cache Miss MySQL Database Source of Truth 1. Check Redis 2. On cache miss 3. Store result 4. Return cached data to client

Cache-Aside: check the cache, fall back to MySQL on a miss, then write the result back to Redis.

Step-by-Step Request Flow

  1. Client sends a request to the Spring Boot REST API.
  2. Spring checks Redis for the requested cache key.
  3. If the key exists, Spring returns the cached result without calling the service method.
  4. If the key does not exist, the service method runs and retrieves data from MySQL.
  5. Spring stores the returned result in Redis.
  6. The next request can reuse the cached result.

The advantage is that the application controls when data enters the cache. The database does not need to know about Redis at all. The disadvantage is that the first request for any key is always slower, because it must query the database.

Treat the cache as a derived layer. If Redis is wiped, the application should still work — just slower. If Redis is treated as the source of truth, a restart becomes a data-loss event.

The Three Spring Cache Annotations

Before building the project, it helps to understand the three annotations Spring provides for caching. Each one answers a different question about what to do with the cache.

@Cacheable

Use @Cacheable when you want to cache the result of a method. On the first call, Spring runs the method and stores the result. On later calls with the same key, Spring returns the cached value and skips the method entirely.

@Cacheable(value = "products", key = "#id")
public ProductResponse getProduct(Long id) {
    return productRepository.findById(id)
        .map(this::toResponse)
        .orElseThrow(() ->
            new RuntimeException("Product not found"));
}

@CachePut

Use @CachePut when you want the method to execute every time and update the cache with its returned value. This is the right choice after an update operation, so the cache does not serve stale data.

@CachePut(value = "products", key = "#id")
public ProductResponse updateProduct(
        Long id, ProductRequest request) {
    // Update product in database
    // Return updated product response
}

@CacheEvict

Use @CacheEvict when you want to remove cached data. This is the standard approach after a delete, so the application does not keep serving a product that no longer exists.

@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
    productRepository.deleteById(id);
}

Quick Comparison

Annotation Purpose Executes method?
@Cacheable Read and cache result Only on cache miss
@CachePut Update cached result Always
@CacheEvict Remove cached result Always

Common Pitfall: Self-Invocation

Spring implements caching through a proxy. If a method inside ProductService calls getProductById on this, the call bypasses the proxy and the cache annotation is ignored. This is the single most common reason caching appears not to work.

// This call will NOT use the cache
public ProductResponse loadAndLog(Long id) {
    return getProductById(id); // self-invocation bypasses the proxy
}

The fix is to extract the cached method into a separate bean, or accept that the internal call will not be cached. For most applications, extracting into a dedicated service is the cleaner choice.

Build the Complete Spring Boot + Redis Application

Now let's implement a working example. We will create a Product Management API with create, read, list, update, and delete operations. Redis handles the caching, and MySQL remains the source of truth.

Spring Boot request path with Redis cache A request flows from the controller to the service. The service checks Redis. On a hit it returns. On a miss it calls the repository, which queries MySQL, then writes to Redis. Spring Boot Cache Request Path Controller @RestController Service @Cacheable @CachePut Redis Cache Repository Data Access MySQL Database Source of Truth hit miss On a miss, the repository result is written back to Redis automatically.

Step 1: Technology Stack

Language Java 17
Framework Spring Boot 3.5.x
Build tool Gradle
Database MySQL 8
Cache Redis 7
ORM Spring Data JPA / Hibernate
API testing Postman or curl

Step 2: Create the Spring Boot Project

Use Spring Initializr with the following settings: Gradle (Groovy), Java 17, Spring Boot 3.5.x, packaging Jar. Add these dependencies: Spring Web, Spring Data JPA, Spring Data Redis, MySQL Driver, and Validation.

Step 3: Configure Gradle Dependencies

Open build.gradle and configure the following dependencies:

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.5.5'
    id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.deepsingh44'
version = '1.0.0'

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

repositories {
    mavenCentral()
}

dependencies {

    implementation 'org.springframework.boot:spring-boot-starter-web'

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

    implementation 'org.springframework.boot:spring-boot-starter-data-redis'

    implementation 'org.springframework.boot:spring-boot-starter-validation'

    runtimeOnly 'com.mysql:mysql-connector-j'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

Important: Spring Boot's dependency management selects compatible Spring Data Redis and Redis client versions. Avoid manually overriding these versions unless you have a specific compatibility requirement.

Step 4: Start Redis with Docker

For local development, Docker is the easiest way to run Redis.

docker run -d \
  --name redis-cache \
  -p 6379:6379 \
  redis:7

On Windows PowerShell, use the single-line form:

docker run -d --name redis-cache -p 6379:6379 redis:7

Verify the container is running:

docker ps

Connect to the Redis CLI and confirm the connection:

docker exec -it redis-cache redis-cli
PING

Expected response:

PONG

Production note: this command is for local development only. Production Redis should use authentication, private networking, TLS where appropriate, persistent deployment configuration, backups where required, and monitored resource limits.

Step 5: Configure MySQL

Create the database:

CREATE DATABASE redis_demo;

Hibernate will generate the product table for this learning example.

Step 6: Configure application.yml

server:
  port: 8080

spring:

  application:
    name: redis-caching-demo

  datasource:
    url: jdbc:mysql://localhost:3306/redis_demo
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

  data:
    redis:
      host: localhost
      port: 6379
      connect-timeout: 2s

  cache:
    type: redis

logging:
  level:
    org.springframework.cache: TRACE

Replace your_password with your local MySQL password. For production, use environment variables or a secret manager instead of committing database credentials to source control.

Step 7: Package Structure

com.deepsingh44
|
|-- RedisCachingApplication.java
|
|-- config
|   |-- RedisConfig.java
|
|-- controller
|   |-- ProductController.java
|
|-- dto
|   |-- ProductRequest.java
|   |-- ProductResponse.java
|
|-- entity
|   |-- Product.java
|
|-- repository
|   |-- ProductRepository.java
|
|-- service
    |-- ProductService.java

Step 8: Create the Product Entity

package com.deepsingh44.entity;

import jakarta.persistence.*;
import java.math.BigDecimal;

@Entity
@Table(name = "products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private BigDecimal price;

    private String category;

    public Product() {
    }

    public Product(String name,
                   BigDecimal price,
                   String category) {
        this.name = name;
        this.price = price;
        this.category = category;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}

Here, JPA annotations map the Java object to the MySQL products table.

Step 9: Create Request and Response DTOs

Keeping API request and response objects separate from database entities is good practice.

package com.deepsingh44.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;

public record ProductRequest(

    @NotBlank(message = "Product name is required")
    String name,

    @NotNull(message = "Price is required")
    @Positive(message = "Price must be greater than zero")
    BigDecimal price,

    @NotBlank(message = "Category is required")
    String category

) {}
package com.deepsingh44.dto;

import java.io.Serializable;
import java.math.BigDecimal;

public record ProductResponse(
    Long id,
    String name,
    BigDecimal price,
    String category
) implements Serializable {}

The response DTO implements Serializable because the default Redis cache value serializer used in this example is Java serialization. For a production application that needs JSON interoperability, explicitly configure and test a suitable JSON serializer. Do not enable unrestricted polymorphic deserialization for untrusted Redis values.

Step 10: Create the Product Repository

package com.deepsingh44.repository;

import com.deepsingh44.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository
        extends JpaRepository<Product, Long> {

}

Spring Data JPA provides the common CRUD operations automatically, so no SQL queries are needed for this basic example.

Step 11: Configure Redis Cache

package com.deepsingh44.config;

import java.time.Duration;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration(proxyBeanMethods = false)
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisCacheManager cacheManager(
            RedisConnectionFactory connectionFactory) {

        RedisCacheConfiguration defaultConfig =
                RedisCacheConfiguration
                    .defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(10))
                    .disableCachingNullValues()
                    .prefixCacheNameWith("deepsingh44::");

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withCacheConfiguration(
                    "products",
                    defaultConfig.entryTtl(
                        Duration.ofMinutes(15)
                    )
                )
                .build();
    }
}

The important configuration options:

  • @EnableCaching: enables Spring's caching infrastructure.
  • RedisConnectionFactory: provides the Redis connection used by Spring Data Redis.
  • RedisCacheManager: manages application caches backed by Redis.
  • entryTtl(): defines how long a cache entry remains valid.
  • disableCachingNullValues(): prevents null results from being stored.
  • prefixCacheNameWith(): namespaces application cache keys.

We have configured a 10-minute default expiration and a 15-minute expiration for the products cache.

Why is TTL important? Without a suitable expiration policy, cached information can remain available longer than intended. TTL provides a time-based safety mechanism, although it does not replace proper cache invalidation.

Step 12: Implement the Product Service

This is the most important part of the application. All caching operations live inside the service layer.

package com.deepsingh44.service;

import com.deepsingh44.dto.ProductRequest;
import com.deepsingh44.dto.ProductResponse;
import com.deepsingh44.entity.Product;
import com.deepsingh44.repository.ProductRepository;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductService {

    private final ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    // Create product
    @Transactional
    public ProductResponse createProduct(ProductRequest request) {

        Product product = new Product(
            request.name(),
            request.price(),
            request.category()
        );

        Product saved = productRepository.save(product);

        return toResponse(saved);
    }

    // Read product with Redis caching
    @Cacheable(
        value = "products",
        key = "#id",
        unless = "#result == null"
    )
    @Transactional(readOnly = true)
    public ProductResponse getProductById(Long id) {

        System.out.println("Fetching product from MySQL: " + id);

        Product product = productRepository.findById(id)
            .orElseThrow(() ->
                new RuntimeException("Product not found: " + id)
            );

        return toResponse(product);
    }

    // Get all products
    @Transactional(readOnly = true)
    public List<ProductResponse> getAllProducts() {

        return productRepository.findAll()
            .stream()
            .map(this::toResponse)
            .toList();
    }

    // Update product and refresh cache
    @Transactional
    @CachePut(
        value = "products",
        key = "#id"
    )
    public ProductResponse updateProduct(
            Long id,
            ProductRequest request) {

        Product product = productRepository.findById(id)
            .orElseThrow(() ->
                new RuntimeException("Product not found: " + id)
            );

        product.setName(request.name());
        product.setPrice(request.price());
        product.setCategory(request.category());

        Product updated = productRepository.save(product);

        return toResponse(updated);
    }

    // Delete product and remove cache
    @Transactional
    @CacheEvict(
        value = "products",
        key = "#id"
    )
    public void deleteProduct(Long id) {

        if (!productRepository.existsById(id)) {
            throw new RuntimeException("Product not found: " + id);
        }

        productRepository.deleteById(id);
    }

    private ProductResponse toResponse(Product product) {

        return new ProductResponse(
            product.getId(),
            product.getName(),
            product.getPrice(),
            product.getCategory()
        );
    }
}

How @Cacheable Works Here

Suppose the client requests product ID 101. Spring generates a cache entry using the products cache and the supplied ID. If a valid entry exists, the service method is skipped. If not, Spring executes the method, fetches the product from MySQL, and stores the returned response in Redis. The unless condition prevents caching a null result.

How @CachePut Works Here

When the product is updated, the method executes and the returned ProductResponse replaces the corresponding cache value.

How @CacheEvict Works Here

When the product is deleted successfully, the corresponding cache entry is removed.

Important production consideration: Spring cache annotations are proxy-based. A method calling another cached method through this inside the same class will generally bypass the cache interceptor. Also, a cache operation and a database transaction are not automatically one atomic operation. For applications requiring strict consistency, consider transaction-aware cache management, after-commit eviction, or an outbox / event-driven invalidation strategy.

Step 13: Create the REST Controller

package com.deepsingh44.controller;

import com.deepsingh44.dto.ProductRequest;
import com.deepsingh44.dto.ProductResponse;
import com.deepsingh44.service.ProductService;

import jakarta.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @PostMapping
    public ResponseEntity<ProductResponse> createProduct(
            @Valid @RequestBody ProductRequest request) {

        return ResponseEntity
            .status(HttpStatus.CREATED)
            .body(productService.createProduct(request));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ProductResponse> getProduct(
            @PathVariable Long id) {

        return ResponseEntity.ok(
            productService.getProductById(id)
        );
    }

    @GetMapping
    public ResponseEntity<List<ProductResponse>> getAllProducts() {

        return ResponseEntity.ok(
            productService.getAllProducts()
        );
    }

    @PutMapping("/{id}")
    public ResponseEntity<ProductResponse> updateProduct(
            @PathVariable Long id,
            @Valid @RequestBody ProductRequest request) {

        return ResponseEntity.ok(
            productService.updateProduct(id, request)
        );
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(
            @PathVariable Long id) {

        productService.deleteProduct(id);

        return ResponseEntity.noContent().build();
    }
}

Step 14: Create the Main Application Class

package com.deepsingh44;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisCachingApplication {

    public static void main(String[] args) {

        SpringApplication.run(
            RedisCachingApplication.class,
            args
        );
    }
}

The basic Spring Boot Redis caching application is now complete.

Testing the Application

Start the Redis container, make sure MySQL is running, and run the Spring Boot application.

API 1: Create a Product

Method: POST — http://localhost:8080/api/products

Request body:

{
  "name": "Dell Laptop",
  "price": 65000,
  "category": "Electronics"
}

Example response:

{
  "id": 1,
  "name": "Dell Laptop",
  "price": 65000,
  "category": "Electronics"
}

API 2: Get Product by ID

Method: GET — http://localhost:8080/api/products/1

First request: the Redis key does not exist, so Spring executes the service method and fetches the product from MySQL. You will see this in the console:

Fetching product from MySQL: 1

Second request: send the exact same request again. Spring finds the product in Redis, the service method is skipped, and the MySQL log message does not appear again. That is your first cache hit.

API 3: Update Product

Method: PUT — http://localhost:8080/api/products/1

{
  "name": "Dell Laptop Pro",
  "price": 72000,
  "category": "Electronics"
}

The update runs against MySQL and refreshes the corresponding Redis cache entry with the updated response.

API 4: Delete Product

Method: DELETE — http://localhost:8080/api/products/1

After a successful delete, the corresponding cache entry is removed. A subsequent GET request will not find the product in MySQL and will return an error.

Verifying Cache Data in Redis

The API works, but how do we confirm that Redis actually contains the cached data?

docker exec -it redis-cache redis-cli
KEYS *

You should see a key similar to:

deepsingh44::products::1

Because Redis stores the value using Java serialization in this configuration, the value may not look like readable JSON. Check the expiration time:

TTL deepsingh44::products::1

Redis returns the remaining lifetime in seconds. A value of -2 means the key does not exist, while -1 means the key exists without an expiration.

For controlled local inspection, you can also watch commands:

MONITOR

Be careful with MONITOR in production — it can expose command data and create significant overhead.

Cache Hits, Misses, and Hit Ratio

Two terms come up constantly when discussing caching.

Cache Hit

The requested data is already available in Redis, so the database is not queried.

Request: GET /api/products/1
Redis:   Key exists
Result:  Return cached response
Database: Not queried

Cache Miss

The requested key is not in Redis, so the service runs and the result is stored back in the cache.

Request: GET /api/products/2
Redis:   Key not found
Result:  Execute service method
Database: Fetch product
Redis:   Store product response

Cache hit ratio is a useful metric for understanding cache effectiveness:

Cache Hit Ratio = Cache Hits / Total Cache Requests * 100

For example, if 8,000 out of 10,000 lookups are hits:

Cache Hit Ratio = 8000 / 10000 * 100
                 = 80%

A high hit ratio is not automatically good. Evaluate it alongside data freshness, memory usage, latency, and business requirements.

Other Redis Caching Strategies

Cache-Aside is not the only strategy. Knowing the alternatives helps when designing high-traffic applications.

1. Cache-Aside

The application checks the cache first. On a miss, it reads from the database and populates the cache.

Best for: product details, user profiles, frequently accessed reference data.

2. Read-Through Cache

The application requests data through the cache layer, and the cache provider loads missing data from the underlying source.

Best for: systems with a cache-loading abstraction that centralizes data loading.

3. Write-Through Cache

When data is written, both the cache and the database are updated as part of the write workflow.

Best for: workloads where keeping cached data updated during writes is important.

4. Write-Behind Cache

Changes are written to the cache first and persisted to the database asynchronously.

Best for: carefully designed high-write workloads where delayed persistence is acceptable and durability is handled properly. This introduces complexity around failures, ordering, retries, and data loss, so it should not be used casually for financial transactions.

Redis Caching in Microservices

Redis becomes especially useful when multiple Spring Boot services need access to frequently requested data.

Microservices sharing a Redis cluster An API gateway routes requests to multiple Spring Boot services. Each service uses a shared Redis cluster for caching, with a database layer as the source of truth. API Gateway User Service Spring Boot Payment Service Spring Boot Other Services Spring Boot Redis Cluster Shared caching infrastructure Database Layer

Multiple services can share a Redis deployment, but they should not automatically share every cache key or cached object. Use clear key namespaces, ownership boundaries, expiration policies, and invalidation mechanisms.

One important design principle: do not cache payment authorization decisions, or transaction states as if they were ordinary product descriptions. Financial operations require authoritative data, concurrency control, and carefully designed consistency guarantees.

Production Best Practices

Adding @Cacheable is easy. Designing a reliable caching strategy is the real engineering challenge.

Production Redis cache checklist Eight production readiness areas for a Redis cache: TTL, selective caching, key design, stampede prevention, failure handling, monitoring, sensitivity, and consistency. Production Readiness Checklist 1. TTL Always set a TTL Add jitter Match business rules 2. Selectivity Cache only hot data Avoid huge objects 3. Key Design Namespace keys Include params 4. Stampede TTL jitter Single-flight load 5. Failure Handling Timeouts & retries Fallback to DB 6. Monitoring Hit / miss ratio Memory & latency 7. Sensitivity Avoid secrets Encrypt if required 8. Consistency Evict after write Accept eventual Verify each area before exposing the cache to production traffic.

1. Always Define a Suitable TTL

Choose an expiration duration based on how frequently the data changes and how stale it is allowed to become.

Data type Illustrative TTL
Static reference data 30 minutes or longer
Product information 5–15 minutes
Dashboard summaries 1–5 minutes
Temporary verification data Business-defined short TTL

These are starting examples, not universal values. Always consider the data's business requirements.

2. Avoid Unnecessary Caching

Not every database query deserves a cache. Frequently changing data, large objects, highly unique queries, and data with strict consistency requirements may not benefit from caching at all.

3. Use Meaningful Cache Keys

Prefer predictable and namespaced keys:

product::101
customer::202
configuration::payment-limits

Include relevant parameters in the key when the result depends on more than one input.

4. Prevent Cache Stampedes

Imagine a popular cache entry expires while thousands of requests arrive simultaneously. Many requests may observe a cache miss and execute the same expensive database query at the same time. This is known as a cache stampede.

Possible solutions include:

  • Use randomized TTLs to avoid synchronized expiration.
  • Use request coalescing or single-flight loading.
  • Use carefully designed distributed locks where appropriate.
  • Refresh important cache entries before expiration.

5. Handle Redis Failures

Redis should not become an unplanned single point of failure for every request. Think about what should happen when Redis becomes unavailable:

  • Should the application fall back to MySQL for safe read operations?
  • Should the request fail when cached data is mandatory?
  • How will you prevent excessive database traffic during Redis outages?

Use connection timeouts, bounded retries, monitoring, and carefully designed fallback behavior. A retry on every request can make an outage worse.

6. Monitor Cache Performance

Monitor metrics such as:

  • Cache hit and miss ratio
  • Redis memory consumption
  • Evictions and expired keys
  • Redis command latency
  • Connection pool usage
  • Cache-related application errors
  • Database query volume

7. Avoid Caching Sensitive Information Unnecessarily

Never assume that Redis is automatically secure simply because it is an internal service. Do not casually cache passwords, authentication secrets, PINs, payment credentials, or sensitive personal information. If a legitimate use case requires sensitive data in a cache, apply appropriate data minimization, access control, encryption, TTL, and security review.

8. Accept Eventual Consistency

A cache operation and a database transaction are not automatically one atomic operation. Choose eviction over writing the new value when a race between concurrent updates is possible, and accept that a cache will always be eventually consistent with the database.

Common Caching Mistakes

Mistake Better approach
No TTL configured Define expiration policies.
Cache never updated after database changes Implement cache update or eviction.
Caching everything Cache based on actual access patterns.
Using unclear keys Use namespaces and consistent naming.
Ignoring Redis outages Design timeout and fallback behavior.
Using KEYS * in production Use targeted lookups or SCAN for controlled inspection.
Ignoring serialization compatibility Use deliberate, versioned serialization contracts.
Assuming Redis and MySQL are one transaction Design consistency and invalidation explicitly.

Redis vs In-Memory Caching

Java developers often ask an important question: why use Redis when Java already provides ConcurrentHashMap? Both store data in memory, but they solve different problems.

Feature ConcurrentHashMap Redis
Storage Application memory Redis server memory
Shared across instances No Yes
Network communication No Yes
TTL support Requires custom logic Built-in expiration
Data structures Java collections Rich Redis data structures
Independent scaling No Yes
Operational overhead Low Requires Redis infrastructure

Use an in-memory cache when local, instance-specific caching is sufficient. Choose Redis when multiple application instances need a shared cache or when Redis-specific features are required.

Improving Redis Caching Performance

  1. Choose the right serialization format: measure serialization and deserialization overhead.
  2. Keep cache values reasonably small: avoid unnecessarily large objects.
  3. Use connection pooling: configure appropriate Redis client resources.
  4. Use pipelining carefully: reduce network round trips for suitable independent operations.
  5. Monitor memory: select an appropriate memory limit and eviction policy.
  6. Optimize key design: avoid excessively large keys and uncontrolled key cardinality.
  7. Measure actual latency: benchmark end-to-end API performance instead of assuming every Redis lookup is free.

Frequently Asked Interview Questions

1. What is Redis?

Redis is an in-memory data store supporting multiple data structures. It is commonly used for caching, messaging, and low-latency data access.

2. Why do we use Redis with Spring Boot?

Redis helps reduce repeated database queries by storing frequently accessed information and serving subsequent requests from the cache. Spring Boot's caching abstraction makes it easy to add without rewriting business logic.

3. What is the difference between @Cacheable and @CachePut?

@Cacheable checks the cache and skips method execution when a valid entry exists. @CachePut always executes the method and updates the cache with its result.

4. What is @CacheEvict?

It removes one or more entries from the cache. It is useful when data is deleted or when an application needs to invalidate cached information.

5. What is TTL in Redis?

TTL stands for Time To Live. It specifies how long a Redis key remains available before expiration.

6. What happens when Redis is unavailable?

Cache operations can fail depending on the connection and application configuration. A production system should define timeouts, monitoring, and safe fallback behavior based on business requirements.

7. What is cache invalidation?

Cache invalidation is the process of removing or updating cached information when its underlying data changes.

8. What is a cache stampede?

It happens when many concurrent requests try to load the same missing or expired cache entry, causing repeated expensive database operations. Randomized TTLs, single-flight loading, and distributed locks help prevent it.

9. Is Redis a replacement for MySQL?

No. They serve different purposes. MySQL is a relational database used for persistent transactional data, while Redis is commonly used for low-latency access and caching.

10. What is the Cache-Aside pattern?

The application first checks the cache. If the data is missing, it retrieves it from the underlying database and then populates the cache.

11. What happens if two application instances update the same cache entry?

Both instances may write competing values. A distributed consistency strategy, versioning, or event-based invalidation may be needed depending on the application requirements.

12. Can we use Redis for payment transactions?

Redis can support auxiliary workloads such as rate limiting, temporary state, and caching reference data. It should not casually replace the authoritative transactional database or ledger for financial operations.

Your Redis Caching Checklist

Before adding a cache to any service, ask:

  • Is this data actually read-heavy? If not, a cache may add complexity without value.
  • How stale is this data allowed to become? The answer determines the TTL.
  • Do I have a clear invalidation path? Every write should evict or refresh the cache.
  • What happens if Redis goes down? Define fallback behavior explicitly.
  • Are my keys namespaced and readable? Use a consistent key convention.
  • Am I caching anything sensitive? If yes, review access control and encryption.
  • Will I monitor hit ratio and latency? Without metrics, you cannot tell whether caching helps.

Start small. Add caching to one growing endpoint and measure the effect before expanding it to the rest of the application.

Best Practices for Java Developers

  • Enable caching with @EnableCaching on a configuration class.
  • Always set a TTL and add jitter to avoid synchronized expiration.
  • Use @CachePut after writes and @CacheEvict after deletes.
  • Keep cached methods in a separate bean to avoid self-invocation issues.
  • Configure JSON serialization for readability and cross-language compatibility.
  • Never use KEYS * in production; use SCAN for targeted inspection.
  • Treat the cache as a derived layer — the application must work when Redis is empty.
  • Write unit and integration tests for cache hit, miss, update, and eviction scenarios.

Conclusion

Redis caching is one of the most useful techniques for improving the performance of Java and Spring Boot applications. But adding a cache is not simply about slapping @Cacheable on a service method. Developers need to understand expiration, invalidation, serialization, concurrency, consistency, and failure handling.

I'll be honest: I don't add Redis to every service. A query that takes 3ms does not need a cache. Small apps with two or three endpoints do not need the operational overhead. But for endpoints that are hit thousands of times per second and compute the same result each time, a Redis cache is one of the highest-leverage changes you can make. The returns are immediate and measurable.

If you are a fresher, start by understanding cache hits, cache misses, and the Cache-Aside pattern. Build the product API from this tutorial and watch the database log messages disappear on the second request. That moment makes the pattern click.

If you are an experienced developer, focus on cache stampedes, transaction boundaries, observability, and consistency across microservices. The interesting problems are not in adding caching — they are in keeping it reliable at scale.

The most important lesson is this: treat the cache as a derived layer, not as storage. Design the application so it still works correctly when Redis is empty, slow, or unavailable. If you can do that, caching becomes a performance tool instead of a reliability risk.

Related topics: Chain of Responsibility Design Pattern in Java, Spring Boot Performance Tuning, Distributed Locking with Redis, Spring Data Redis Configuration Guide, Cache Invalidation Strategies, Java Design Patterns with Real-World Examples


Keep Learning Java and Spring Boot

Enjoyed this tutorial? Explore more practical Java, Spring Boot, Hibernate, microservices, and system design articles on the blog.

Have you implemented Redis caching in a real-world Spring Boot application? Share your experience in the comments.