Build a caching layer for an application using AWS ElastiCache and demonstrate:
- Reducing database load
- Improving application response time
- Using Redis as an in-memory cache
- Understanding cache hit and cache miss scenarios
- Scaling applications using distributed caching
Amazon ElastiCache is a fully managed in-memory caching service that supports:
- Redis
- Memcached
It stores frequently accessed data in memory rather than retrieving it from a database every time.
Because RAM is much faster than disk storage, applications respond significantly faster.
Without cache:
User
|
v
Application
|
v
Database
Every request hits the database.
Problems:
- High latency
- Increased DB load
- Expensive database scaling
With cache:
User
|
v
Application
|
v
ElastiCache
|
+---- Cache Hit --> Return Data
|
+---- Cache Miss --> Database
Most requests never reach the database.
Imagine your Network Nuts LMS.
Student opens:
Course Details
10,000 students may request:
RHCSA Course Information
Without cache:
10,000 Database Queries
With cache:
1 Database Query
9999 Cache Reads
Application
|
v
ElastiCache
|
+------ Found?
| |
| Yes
| |
| v
| Return Data
|
No
|
v
Database
|
v
Store in Cache
| Feature | Redis | Memcached |
|---|---|---|
| Data Structures | Yes | No |
| Persistence | Yes | No |
| Replication | Yes | Limited |
| Pub/Sub | Yes | No |
| Popularity | Very High | Moderate |
Most modern applications use Redis.
User
|
v
FastAPI Application
|
v
ElastiCache Redis
|
v
RDS PostgreSQL
Services Used:
- EC2
- ElastiCache Redis
- RDS PostgreSQL
- IAM
- CloudWatch
Create a student lookup API.
Request:
GET /student/1
Application:
- Check Redis
- If found → return data
- If not found → query PostgreSQL
- Store result in Redis
Launch:
Amazon RDS
Example database:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
course VARCHAR(100)
);Insert sample data:
INSERT INTO students VALUES
(1,'Aryan','DevOps'),
(2,'Rahul','AWS'),
(3,'Neha','Kubernetes');Navigate:
ElastiCache
→ Redis OSS
→ Create Cluster
Configuration:
Cluster Mode Disabled
Node Type: cache.t3.micro
Lab-friendly and inexpensive.
Install:
pip install fastapi uvicorn redis psycopg2-binaryimport redis
redis_client = redis.Redis(
host="redis-endpoint",
port=6379,
decode_responses=True
)import psycopg2
conn = psycopg2.connect(
host="rds-endpoint",
database="studentdb",
user="postgres",
password="password"
)from fastapi import FastAPI
app = FastAPI()
@app.get("/student/{student_id}")
def get_student(student_id: int):
cache_key = f"student:{student_id}"
cached = redis_client.get(cache_key)
if cached:
return {
"source": "cache",
"data": cached
}
cur = conn.cursor()
cur.execute(
"SELECT * FROM students WHERE id=%s",
(student_id,)
)
result = cur.fetchone()
redis_client.setex(
cache_key,
300,
str(result)
)
return {
"source": "database",
"data": result
}First request:
curl http://server/student/1Response:
{
"source":"database",
"data":[1,"Aryan","DevOps"]
}Flow:
Redis Miss
|
v
Database Query
|
v
Store in Redis
Second request:
curl http://server/student/1Response:
{
"source":"cache",
"data":"[1,'Aryan','DevOps']"
}Database not accessed.
Add artificial DB delay:
import time
time.sleep(2)Results:
| Request | Response Time |
|---|---|
| Cache Miss | ~2 sec |
| Cache Hit | ~5 ms |
Easy demonstration for students.
Connect:
redis-cliCommands:
KEYS *Output:
student:1
student:2
student:3
Check value:
GET student:1Check remaining TTL:
TTL student:1Example:
250
After expiration:
Key Removed Automatically
Next request hits database again.
Monitor:
CPU Usage
Memory Usage
Cache Hits
Cache Misses
Network Throughput
Evictions
Useful metrics:
CacheHitRate
CurrConnections
BytesUsedForCache
Website
|
v
Redis Cache
|
v
Product Database
Product information is heavily cached.
Student Portal
|
v
Redis
|
v
Course Database
Popular course pages are cached.
Instead of storing sessions locally:
Application
|
v
Redis
All servers share the same session store.
Very relevant to your RAG applications.
User Query
|
v
Redis Cache
|
v
OpenAI API
Repeated questions:
"What is Kubernetes?"
can be served from cache.
This reduces:
- OpenAI cost
- Response time
App Server 1
|
App Server 2
|
App Server 3
|
v
Redis Cluster
All application instances share the same cache.
Store request counters:
user:123:requests
Redis tracks API usage.
Used extensively in:
- APIs
- SaaS products
- Authentication systems
Redis Sorted Sets:
ZADD leaderboard 100 Aryan
ZADD leaderboard 80 RahulQuery:
ZREVRANGE leaderboard 0 9Useful for:
- Gaming
- Training Platforms
- Rankings
Redis
|
v
Reduce DB Load
Login Sessions
JWT Metadata
User Context
Weather APIs
Stock APIs
AI Responses
Redis can also be used for:
Background Jobs
Task Queues
though for AWS-native queues, SQS is usually preferred.
Answer: A fully managed in-memory caching service that supports Redis and Memcached.
Answer: Redis stores data in RAM rather than reading from disk-based database storage.
Answer: Requested data is found in cache and returned without querying the database.
Answer: Data is not present in cache, so the application retrieves it from the database and stores it in cache.
Answer: Time To Live. It determines how long a cache entry remains before automatic expiration.
Answer: Redis reduces database load, lowers latency, and improves application scalability.
After completing this lab, students should understand:
- What caching is and why it is important.
- Redis fundamentals.
- Cache hit vs cache miss.
- TTL and cache expiration.
- Database query caching.
- Session storage architectures.
- Distributed caching concepts.
- CloudWatch monitoring for Redis.
- Cost and performance benefits of caching.
- Real-world cloud-native architectures using ElastiCache.