Middle
How can a cache be implemented on the backend? What are the methods?
sobes.tech AI
Answer from AI
Caching on the backend can be implemented in several ways:
-
In-memory application cache — storing data in RAM (e.g., using dictionaries, LRU caches). Fast, but limited by server resources and not suitable for scalable systems.
-
External cache systems — Redis, Memcached. Allow centralized cache storage, providing high access speed and scalability.
-
HTTP caching — using Cache-Control headers, ETag for caching responses at the HTTP level.
-
Database-level caching — for example, Materialized Views, indexes, or built-in caching mechanisms.
-
CDN caching — for static content and API responses.
Example of using Redis to cache query results in Python:
import redis
cache = redis.Redis(host='localhost', port=6379)
key = 'user_123_profile'
cached_data = cache.get(key)
if cached_data:
profile = cached_data
else:
profile = get_profile_from_db(123) # function to fetch from DB
cache.set(key, profile, ex=3600) # cache for an hour