[Atomic Glue](atomicglue.co)
BACKEND
Home › Glossary › Backend· 62 ·

Caching (Redis)

\\kash-ing red-is\\n.
Filed underBackendSoftware EngineeringPerformanceInfrastructureAnalytics
In brief · quick answer

Caching is the technique of storing frequently accessed data in a fast, temporary storage layer to serve future requests faster. Redis is the most popular in-memory data store used for caching, providing sub-millisecond response times.

§ 1 Definition

Caching is a performance optimization strategy built on a simple principle: store expensive-to-compute data in a fast-access storage layer so subsequent requests can skip the expensive operation. The expensive operation could be a database query, an API call, a complex computation, or a file read. Redis is an open-source, in-memory data structure store that serves as the industry standard caching layer. It stores data in RAM rather than on disk, achieving sub-millisecond response times. Redis supports data structures beyond simple key-value: strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, streams, and geospatial indexes. This versatility makes Redis useful far beyond caching: real-time leaderboards, rate limiting, session storage, message queues (pub/sub and streams), distributed locks, and feature flags. The Cache-Aside pattern is the most common caching strategy: on a read, check the cache first. If found (cache hit), return it. If not found (cache miss), load from the database, store in cache, and return. On a write, invalidate or update the cache entry. The most important caching decision is what to cache and for how long (TTL). Cache everything that is expensive to compute and frequently accessed. Never cache user-specific data without proper invalidation.

§ 2 Caching Strategies

Five main caching strategies exist. Cache-Aside (lazy loading): application checks cache, loads from DB on miss, stores in cache for next time. The most common and safest pattern. Read-Through: the cache layer automatically loads from the database on a miss. The application is simpler but the cache is more complex. Write-Through: every write goes to both cache and database in the same transaction. Data is always consistent but writes are slower. Write-Behind (Write-Back): writes go to cache which asynchronously persists to the database. Fast writes but data loss risk if the cache fails. Write-Around: writes go directly to the database, only invalidating the cache. Good for data that is written once and read infrequently. The choice depends on your read/write ratio, consistency requirements, and tolerance for staleness. Cache-Aside is the default choice for most web applications.

§ 3 Redis Data Structures and Use Cases

Redis is often described as a 'key-value store,' but its real power is its data structures. Strings with TTL for simple caching: set('user:42', data, 'EX', 3600). Hashes for structured objects that need field-level access: hset('user:42', 'name', 'Alice'). Lists for message queues: lpush('queue:tasks', task). Sets for unique collections and membership checks: sadd('post:5:likes', 'user:42'). Sorted sets for leaderboards: zadd('leaderboard', score, userId). Streams for event sourcing and log aggregation: xadd('events', '*', 'type', 'purchase', 'amount', '10.99'). HyperLogLogs for approximate unique counts (page views, unique visitors). Geospatial indexes for location-based queries. The right data structure eliminates entire classes of backend complexity.

§ 4 Cache Invalidation: The Hard Problem

Cache invalidation is one of the two hard things in computer science (along with naming things and off-by-one errors). Stale data is the cost of caching, and managing staleness is the hard part. The simplest approach is Time-To-Live (TTL): entries expire automatically after a set duration. Trade off: shorter TTL means more cache misses (lower benefit), longer TTL means more stale data. Active invalidation: when data changes, explicitly delete or update the cache entry. The most reliable pattern: on a write, delete the cache entry (not update it). The next read will miss, load the fresh data from the database, and populate the cache. This avoids race conditions where the cached data is out of sync with the database. For distributed systems, cache invalidation requires propagating invalidation events across all instances. Redis pub/sub, message queues, and cache stamps (exponential backoff on cache miss to prevent thundering herd) are common solutions.

§ 5 Note

Common misunderstanding: Caching is not just about speed. It is also about reducing load on downstream systems. A cache hit means one fewer database query, one fewer API call, or one fewer computation. This protects your database from overload during traffic spikes. Another misconception: Redis is a cache. Redis is an in-memory data store that is excellent for caching, but it is also a message broker, a real-time data structure server, a rate limiter, and a session store. Calling Redis 'just a cache' misses most of its value. Also: more caching is not always better. Caching adds complexity, memory cost, and potential staleness. Cache what is expensive and frequently accessed. Do not cache everything.

§ 6 In code

```typescript
// Redis caching with ioredis (TypeScript)
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function getUser(id: string) {
  const cacheKey = `user:${id}`;
  
  // Try cache first
  const cached = await redis.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }
  
  // Cache miss: load from database
  const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
  
  // Store in cache with 1-hour TTL
  await redis.setex(cacheKey, 3600, JSON.stringify(user));
  
  return user;
}

async function updateUser(id: string, data: any) {
  // Update database
  await db.query('UPDATE users SET name = $1 WHERE id = $2', [data.name, id]);
  
  // Invalidate cache (delete, don't update)
  await redis.del(`user:${id}`);
}
```

§ 7 Common questions

Q. When should I add caching to my application?
A. When you identify a database query or computation that is slow (or expensive) and frequently repeated with the same parameters. Measure first, then cache.
Q. What happens if Redis goes down?
A. Your application should degrade gracefully. Every cache read must have a fallback that reads from the database. A Redis outage should cause higher latency, not errors.
Q. Redis vs Memcached: which should I use?
A. Redis. Memcached is simpler and uses less memory for simple key-value caching, but Redis's data structures, persistence, replication, and pub/sub make it dramatically more versatile. There is almost no reason to choose Memcached for new projects.
Key takeaways
  • Caching stores frequently accessed data in fast storage (RAM) to avoid expensive recomputation.
  • Redis is the industry standard caching layer, providing sub-millisecond reads and versatile data structures.
  • Cache-Aside with TTL is the default strategy. Invalidate by deleting, not updating, cached entries.
  • Caching reduces database load as much as it improves response times.
How Atomic Glue helps

Atomic Glue integrates Redis caching into every application that needs performance optimization. We use the Cache-Aside pattern with sensible TTLs, graceful degradation if Redis is unavailable, and Redis data structures for real-time features (leaderboards, rate limiting, pub/sub). Caching is a standard performance optimization in our Web Development services. Get in touch to optimize your application's performance.

Get in touch
# Caching (Redis)

Caching is the technique of storing frequently accessed data in a fast, temporary storage layer to serve future requests faster. Redis is the most popular in-memory data store used for caching, providing sub-millisecond response times.

Category: Backend (also: Software Engineering, Performance, Infrastructure, Analytics)

Author: Atomic Glue Development Team

## Definition

Caching is a performance optimization strategy built on a simple principle: store expensive-to-compute data in a fast-access storage layer so subsequent requests can skip the expensive operation. The expensive operation could be a database query, an API call, a complex computation, or a file read. Redis is an open-source, in-memory data structure store that serves as the industry standard caching layer. It stores data in RAM rather than on disk, achieving sub-millisecond response times. Redis supports data structures beyond simple key-value: strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, streams, and geospatial indexes. This versatility makes Redis useful far beyond caching: real-time leaderboards, rate limiting, session storage, message queues (pub/sub and streams), distributed locks, and feature flags. The Cache-Aside pattern is the most common caching strategy: on a read, check the cache first. If found (cache hit), return it. If not found (cache miss), load from the database, store in cache, and return. On a write, invalidate or update the cache entry. The most important caching decision is what to cache and for how long (TTL). Cache everything that is expensive to compute and frequently accessed. Never cache user-specific data without proper invalidation.

## Caching Strategies

Five main caching strategies exist. Cache-Aside (lazy loading): application checks cache, loads from DB on miss, stores in cache for next time. The most common and safest pattern. Read-Through: the cache layer automatically loads from the database on a miss. The application is simpler but the cache is more complex. Write-Through: every write goes to both cache and database in the same transaction. Data is always consistent but writes are slower. Write-Behind (Write-Back): writes go to cache which asynchronously persists to the database. Fast writes but data loss risk if the cache fails. Write-Around: writes go directly to the database, only invalidating the cache. Good for data that is written once and read infrequently. The choice depends on your read/write ratio, consistency requirements, and tolerance for staleness. Cache-Aside is the default choice for most web applications.

## Redis Data Structures and Use Cases

Redis is often described as a 'key-value store,' but its real power is its data structures. Strings with TTL for simple caching: set('user:42', data, 'EX', 3600). Hashes for structured objects that need field-level access: hset('user:42', 'name', 'Alice'). Lists for message queues: lpush('queue:tasks', task). Sets for unique collections and membership checks: sadd('post:5:likes', 'user:42'). Sorted sets for leaderboards: zadd('leaderboard', score, userId). Streams for event sourcing and log aggregation: xadd('events', '*', 'type', 'purchase', 'amount', '10.99'). HyperLogLogs for approximate unique counts (page views, unique visitors). Geospatial indexes for location-based queries. The right data structure eliminates entire classes of backend complexity.

## Cache Invalidation: The Hard Problem

Cache invalidation is one of the two hard things in computer science (along with naming things and off-by-one errors). Stale data is the cost of caching, and managing staleness is the hard part. The simplest approach is Time-To-Live (TTL): entries expire automatically after a set duration. Trade off: shorter TTL means more cache misses (lower benefit), longer TTL means more stale data. Active invalidation: when data changes, explicitly delete or update the cache entry. The most reliable pattern: on a write, delete the cache entry (not update it). The next read will miss, load the fresh data from the database, and populate the cache. This avoids race conditions where the cached data is out of sync with the database. For distributed systems, cache invalidation requires propagating invalidation events across all instances. Redis pub/sub, message queues, and cache stamps (exponential backoff on cache miss to prevent thundering herd) are common solutions.

## Note

Common misunderstanding: Caching is not just about speed. It is also about reducing load on downstream systems. A cache hit means one fewer database query, one fewer API call, or one fewer computation. This protects your database from overload during traffic spikes. Another misconception: Redis is a cache. Redis is an in-memory data store that is excellent for caching, but it is also a message broker, a real-time data structure server, a rate limiter, and a session store. Calling Redis 'just a cache' misses most of its value. Also: more caching is not always better. Caching adds complexity, memory cost, and potential staleness. Cache what is expensive and frequently accessed. Do not cache everything.

## In code

## Common questions
Q: When should I add caching to my application?
A: When you identify a database query or computation that is slow (or expensive) and frequently repeated with the same parameters. Measure first, then cache.
Q: What happens if Redis goes down?
A: Your application should degrade gracefully. Every cache read must have a fallback that reads from the database. A Redis outage should cause higher latency, not errors.
Q: Redis vs Memcached: which should I use?
A: Redis. Memcached is simpler and uses less memory for simple key-value caching, but Redis's data structures, persistence, replication, and pub/sub make it dramatically more versatile. There is almost no reason to choose Memcached for new projects.

## Key takeaways

## Related entries


Last updated June 2026. Permalink: atomicglue.co/glossary/caching-redis

Schedule a call

30 min · Video call

1
Date
2
Time
3
Details