Concept Flow - Why caching matters for performance
Request comes in
Check cache for data
Store data in cache
Return data
This flow shows how caching checks for stored data first to avoid slow data fetching, improving performance.
public String getData(String key) {
if(cache.containsKey(key)) {
return cache.get(key);
}
String data = fetchFromDB(key);
cache.put(key, data);
return data;
}| Step | Action | Cache Contains Key? | Data Source | Cache Update | Returned Data |
|---|---|---|---|---|---|
| 1 | Request with key 'user123' | No | Fetch from DB | Cache stores 'user123' data | Data from DB |
| 2 | Request with key 'user123' | Yes | No DB fetch | No change | Cached data |
| 3 | Request with key 'user456' | No | Fetch from DB | Cache stores 'user456' data | Data from DB |
| 4 | Request with key 'user123' | Yes | No DB fetch | No change | Cached data |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| cache | {} | {'user123': 'Data from DB'} | {'user123': 'Data from DB'} | {'user123': 'Data from DB', 'user456': 'Data from DB'} | {'user123': 'Data from DB', 'user456': 'Data from DB'} |
Caching stores data temporarily to avoid repeated slow operations. Check cache first: if data exists, return it immediately. If not, fetch data, store it in cache, then return. This reduces response time and load on data sources. In Spring Boot, caching improves app performance by reusing data.