Junior — Middle
Explain the principle of operation and purpose of request caching in systems.
sobes.tech AI
Answer from AI
Query caching is a mechanism for storing the results of query executions (for example, to a database or external API) for reuse without re-executing the query. This improves system performance, reduces server load, and decreases response time.
Working principle:
- When a query is executed for the first time, the result is stored in the cache.
- For subsequent requests with the same parameters, the system first checks the cache.
- If the data exists and is up-to-date, the cached result is returned.
- If the data does not exist or is outdated, the query is executed again, and the result updates the cache.
Purpose:
- Accelerate query processing.
- Reduce load on the database or external services.
- Increase scalability and responsiveness of the application.
Example in Java using a simple Map for caching results:
Map<String, String> cache = new HashMap<>();
public String getData(String param) {
if (cache.containsKey(param)) {
return cache.get(param); // return cached data
}
String result = fetchDataFromDB(param); // long query
cache.put(param, result); // store in cache
return result;
}