Spring Boot with Amazon ElastiCache Redis
Learn how to integrate Spring Boot with Amazon ElastiCache Redis step by step. This guide covers Redis architecture, caching strategies, Spring Cache, RedisTemplate, cache eviction, TTL, session storage, and production best practices.
Introduction
As applications grow, databases become one of the biggest performance bottlenecks.
Every user request that directly hits the database increases:
- Response time
- CPU utilization
- Database connections
- Infrastructure cost
Instead of querying the database repeatedly, applications store frequently accessed data in memory.
Amazon ElastiCache for Redis is AWS's fully managed in-memory caching service that provides extremely fast data access with microsecond latency.
In this article, we will integrate Spring Boot with Amazon ElastiCache Redis and implement enterprise caching using Spring Cache.
Learning Objectives
After completing this article, you will understand:
- What is Redis?
- Why use caching?
- Amazon ElastiCache Architecture
- Cache Aside Pattern
- Read Through Cache
- Write Through Cache
- TTL
- Cache Eviction
- Spring Cache
- RedisTemplate
- Spring Boot Integration
- Production Best Practices
Why Caching?
Without caching:
User Request
↓
Spring Boot
↓
Database
↓
Response
Every request goes to the database.
Problems:
- High latency
- Database overload
- Slow APIs
- Higher infrastructure cost
With Redis Cache
User Request
↓
Spring Boot
↓
Redis Cache
↓
Database (Only if Cache Miss)
Benefits:
- Faster response
- Lower database load
- Better scalability
- Improved user experience
What is Amazon ElastiCache?
Amazon ElastiCache is a fully managed in-memory caching service.
Supported engines:
- Redis
- Memcached
Redis is the most popular option for Spring Boot applications.
Redis Characteristics
- In-memory database
- Key-Value store
- Extremely fast
- Supports TTL
- Supports Pub/Sub
- Supports Streams
- Supports Transactions
- Supports Persistence
High-Level Architecture
flowchart LR
USER[Client]
API[Spring Boot]
REDIS[(Redis Cache)]
DB[(Amazon RDS)]
USER --> API
API --> REDIS
API --> DB
Enterprise Architecture
flowchart TD
Users
ALB
SpringBoot
Redis
AmazonRDS
CloudWatch
Users --> ALB
ALB --> SpringBoot
SpringBoot --> Redis
SpringBoot --> AmazonRDS
SpringBoot --> CloudWatch
Real-Time Use Cases
Redis is commonly used for:
- User Sessions
- Product Catalog
- OTP Storage
- Shopping Cart
- API Response Cache
- Leaderboards
- Authentication Tokens
- Frequently Accessed Data
Cache Aside Pattern
Most commonly used caching strategy.
flowchart LR
Client
SpringBoot
Redis
Database
Client --> SpringBoot
SpringBoot --> Redis
Redis --> Database
Flow:
- Check Redis
- Cache Hit → Return
- Cache Miss → Query Database
- Store in Redis
- Return Response
Cache Hit
Request
↓
Redis
↓
Data Found
↓
Return Response
Very fast.
Cache Miss
Request
↓
Redis
↓
No Data
↓
Database
↓
Redis
↓
Response
Read Through Cache
Application requests data.
Cache automatically loads data from database.
Useful in managed caching systems.
Write Through Cache
Application
↓
Redis
↓
Database
Both cache and database stay synchronized.
Write Behind Cache
Application
↓
Redis
↓
Background Sync
↓
Database
Improves write performance.
Cache TTL
TTL
Time To Live
Example:
User Profile
↓
Cache
↓
30 Minutes
After expiration:
Redis removes the entry automatically.
Cache Eviction
Redis removes old data when memory is full.
Policies include:
- LRU
- LFU
- FIFO
- Random
Most applications use:
LRU
Least Recently Used.
ElastiCache Components
| Component | Description |
|---|---|
| Cluster | Redis deployment |
| Node | Redis server |
| Primary | Read & Write |
| Replica | Read only |
| Endpoint | Connection URL |
| Parameter Group | Redis settings |
Prerequisites
Install:
Java 17
Maven
AWS CLI
Spring Boot
Create:
Amazon ElastiCache Redis Cluster
Step 1 Create Redis Cluster
AWS Console
↓
Amazon ElastiCache
↓
Redis OSS
↓
Create Cluster
Cluster Configuration
Cluster Name
codewithvenu-redis
Node Type
cache.t4g.micro
Learning purpose.
Connectivity
Place Redis inside your VPC.
Security Group:
Allow
6379
Only from Spring Boot application.
Step 2 Create Spring Boot Project
Dependencies
- Spring Web
- Spring Data Redis
- Cache
- Actuator
Maven Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
application.yml
spring:
cache:
type: redis
data:
redis:
host: codewithvenu-redis.xxxxxx.cache.amazonaws.com
port: 6379
Enable Caching
@SpringBootApplication
@EnableCaching
public class Application{
}
Redis Configuration
@Configuration
public class RedisConfig {
}
Cache Entity
public class Employee {
private Long id;
private String name;
}
Repository
public interface EmployeeRepository
extends JpaRepository<Employee,Long>{
}
Cacheable Example
@Cacheable("employees")
public Employee getEmployee(Long id){
}
First request
↓
Database
↓
Redis
Second request
↓
Redis
Cache Put
@CachePut("employees")
Updates cache immediately.
Cache Evict
@CacheEvict("employees")
Removes cached object.
Useful after delete.
REST API
Create Employee
POST
/employees
Get Employee
GET
/employees/100
Flow
flowchart LR
Client
Controller
Redis
Database
Client --> Controller
Controller --> Redis
Redis --> Database
Update Employee
PUT
/employees/100
Delete Employee
DELETE
/employees/100
Session Storage
Instead of storing user session inside Spring Boot,
Store session in Redis.
Benefits:
- Multiple application servers
- Shared sessions
- High availability
JWT Token Cache
Redis stores:
- Refresh Tokens
- Blacklisted Tokens
- OTP
- Login Sessions
Shopping Cart
User adds product.
↓
Redis
↓
Instant update
↓
Database later.
Product Catalog
Popular products remain cached.
Database receives fewer requests.
Leaderboard
Gaming applications store rankings in Redis Sorted Sets.
Very fast.
OTP Storage
Generate OTP
↓
Redis
↓
TTL
↓
Automatic deletion
Redis Data Structures
Redis supports:
- String
- List
- Set
- Hash
- Sorted Set
- Stream
- Bitmap
Monitoring
CloudWatch Metrics
Monitor:
- CPU
- Memory
- Connections
- Cache Hits
- Cache Misses
- Evictions
Cache Hit Ratio
Formula
Cache Hits
/
Total Requests
Target
Above
90%
Production Architecture
flowchart TD
Users
ALB
SpringBoot
Redis
Aurora
CloudWatch
Users --> ALB
ALB --> SpringBoot
SpringBoot --> Redis
SpringBoot --> Aurora
SpringBoot --> CloudWatch
Common Errors
Connection Refused
Check:
- Security Group
- Redis Endpoint
- Port 6379
Cache Not Working
Verify:
@EnableCaching
is enabled.
Serialization Error
Configure Redis serializer.
High Memory Usage
Reduce TTL
or
Increase cluster size.
Best Practices
- Cache frequently accessed data
- Never cache everything
- Use TTL
- Evict stale cache
- Monitor hit ratio
- Keep Redis private
- Enable encryption
- Use Spring Cache abstraction
- Use RedisTemplate for advanced operations
- Use replication for HA
- Avoid very large objects
- Use CloudWatch alarms
Redis vs RDS
| Feature | Redis | RDS |
|---|---|---|
| Storage | Memory | Disk |
| Speed | Microseconds | Milliseconds |
| Persistence | Optional | Yes |
| Transactions | Limited | Full |
| Best For | Cache | Database |
Interview Questions
What is Amazon ElastiCache?
A managed in-memory caching service provided by AWS.
Why use Redis?
To reduce database load and improve application performance.
What is Cache Aside?
Application checks cache first.
If data is missing, it queries the database and stores the result in cache.
What is TTL?
Time To Live.
Redis automatically removes expired keys.
Difference between @Cacheable and @CacheEvict?
@Cacheable stores and retrieves cached data.
@CacheEvict removes cached data.
Can Redis replace a database?
No.
Redis is primarily used as a cache and should complement a persistent database such as Amazon RDS or Aurora.
Summary
In this article, we integrated Spring Boot with Amazon ElastiCache Redis.
We covered:
- Redis fundamentals
- ElastiCache architecture
- Cache patterns
- Spring Cache
- RedisTemplate
- TTL
- Cache eviction
- Session storage
- JWT caching
- Shopping cart caching
- Monitoring
- Production best practices
Amazon ElastiCache Redis is one of the most valuable performance optimization services for enterprise Spring Boot applications. When used correctly, it can dramatically reduce database load, lower response times, and improve scalability.
Comments
Share a question, correction, or practical insight about this article.
Checking login status...
Loading approved comments...