Back to Caching: Spring Cache & Redis
Q4Question 4 of 5

How do you handle cache invalidation and keep cached data consistent

Answer: Cache invalidation is the process of detecting when cached data becomes stale and either removing it or refreshing it so that subsequent reads return accurate data from the source of truth.

Key Concepts
  • Cache invalidation is the process of removing or updating stale cached data when the source of truth (database) changes.
  • Cache-aside (lazy loading) reads from cache first, falls back to the database on a miss, and populates the cache on read.
  • Write-through updates the cache and the database in the same operation, keeping both in sync at the cost of write latency.
  • Write-behind (write-back) writes to the cache immediately and asynchronously flushes to the database, risking data loss on failure.
  • TTL (Time To Live) provides a safety net by automatically expiring stale entries even if invalidation logic fails.
  • Event-driven invalidation uses Kafka or another message broker to notify all service instances when data changes.
  • The two hardest problems in computer science are cache invalidation and naming things.

Definition

Cache invalidation is the process of detecting when cached data becomes stale and either removing it or refreshing it so that subsequent reads return accurate data from the source of truth.
  • Cache invalidation removes or updates cached entries when the underlying data in the database changes, preventing clients from reading stale values.
  • Cache-aside (lazy loading) is the most common pattern: check the cache first, fetch from the database on a miss, and store the result in the cache.
  • Write-through updates the cache at the same time as the database, within the same operation, so the cache is always current.
  • Write-behind (write-back) writes to the cache first and asynchronously persists to the database, providing low write latency but risking data loss.
  • TTL (Time To Live) is a timer on each cache entry that automatically deletes it after a set duration, providing a safety net against stale data.

Think of the account balance displayed on the ATM screen at National Bank of India. The ATM caches the balance from the last database query. If Priya makes a deposit at the counter, the cached balance on the ATM is now stale. Cache invalidation is the process of telling the ATM to discard the old balance so the next check fetches the updated number from the database. Without invalidation, the ATM shows the old balance indefinitely. With TTL, the ATM automatically refreshes every 60 seconds even if no one explicitly tells it to.

Understanding the Concepts

What is cache invalidation?

Cache invalidation is the process of keeping cached data in sync with the database. When a value changes in the database, the corresponding cache entry must be removed or updated. If you fail to invalidate, clients read stale data.

In a banking system, stale balances can cause incorrect transfers, duplicate payments, or regulatory violations. Cache invalidation is not optional.

JAVA
package com.bank.service;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;

@Service
public class AccountService {

    private final AccountRepository repository;

    public AccountService(AccountRepository repository) {
        this.repository = repository;
    }

    // Read: cache-aside. Check cache first, then database.
    @Cacheable(value = "accounts", key = "#accountId")
    public AccountResponse findById(String accountId) {
        // This runs ONLY on cache miss
        Account account = repository.findById(accountId)
            .orElseThrow(() -> new AccountNotFoundException(accountId));
        return toResponse(account);
    }

    // Write: evict the cache entry when the account is updated
    @CacheEvict(value = "accounts", key = "#accountId")
    public void updateBalance(String accountId, BigDecimal newBalance) {
        Account account = repository.findById(accountId).orElseThrow();
        account.setBalance(newBalance);
        repository.save(account);
        // @CacheEvict removes "accounts::SAV2001" from Redis
    }

    private AccountResponse toResponse(Account account) {
        return new AccountResponse(
            account.getAccountId(),
            account.getHolderName(),
            account.getBalance(),
            account.getType());
    }
}
TEXT
// First call: cache MISS, reads from database
findById("SAV2001") -> DB query -> cache SET accounts::SAV2001

// Second call: cache HIT, no database query
findById("SAV2001") -> cache GET -> returns immediately

// Update balance: evicts cache
updateBalance("SAV2001", 70000) -> DB update -> cache DELETE accounts::SAV2001

// Next call: cache MISS again, reads fresh data from database
findById("SAV2001") -> DB query -> cache SET accounts::SAV2001 (balance: 70000)

What is the cache-aside pattern?

Cache-aside (also called lazy loading) is the most common caching strategy. The application manages both the cache and the database explicitly.

  • On read:
  • Check the cache.
  • If the value is there (cache hit), return it.
  • If not (cache miss), query the database.
  • Store the result in the cache.
  • Return the result.
  • On write:
  • Update the database.
  • Delete the cache entry (invalidate).
JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.Duration;

@Service
public class BalanceCacheService {

    private static final Duration CACHE_TTL = Duration.ofSeconds(60);

    private final StringRedisTemplate redis;
    private final AccountRepository repository;

    public BalanceCacheService(StringRedisTemplate redis,
            AccountRepository repository) {
        this.redis = redis;
        this.repository = repository;
    }

    public BigDecimal getBalance(String accountId) {
        String key = "balance:" + accountId;

        // Step 1: Check cache
        String cached = redis.opsForValue().get(key);
        if (cached != null) {
            return new BigDecimal(cached); // Cache hit
        }

        // Step 2: Cache miss, query database
        BigDecimal balance = repository.findBalance(accountId);

        // Step 3: Populate cache with TTL
        redis.opsForValue().set(key, balance.toPlainString(),
            CACHE_TTL);

        return balance;
    }

    public void updateBalance(String accountId, BigDecimal newBalance) {
        // Step 1: Update database first
        repository.updateBalance(accountId, newBalance);

        // Step 2: Invalidate cache
        redis.delete("balance:" + accountId);
    }
}
TEXT
// Cache-aside flow:
getBalance("SAV2001")
  -> Redis GET balance:SAV2001 -> null (MISS)
  -> DB SELECT balance FROM accounts WHERE account_id = 'SAV2001'
  -> Redis SET balance:SAV2001 "75000.00" EX 60
  -> return 75000.00

updateBalance("SAV2001", 70000)
  -> DB UPDATE accounts SET balance = 70000 WHERE account_id = 'SAV2001'
  -> Redis DEL balance:SAV2001

How do caching strategies compare?

StrategyRead LatencyWrite LatencyConsistencyData Loss Risk
Cache-asideLow on hit, high on missNormal (DB write + cache delete)EventualNone
Write-throughLow on hitHigher (DB + cache write)StrongNone
Write-behindLow on hitVery low (cache write only)EventualYes (if cache fails before flush)
Read-throughLow on hitNormalEventualNone

For banking systems, cache-aside with TTL is the safest default. Write-behind is too risky for financial data because a Redis failure could lose unflushed balance updates.

JAVA
// Write-through: update cache AND database together
public void writeThrough(String accountId, BigDecimal balance) {
    // Update database
    repository.updateBalance(accountId, balance);

    // Update cache (not delete, but SET)
    redis.opsForValue().set("balance:" + accountId,
        balance.toPlainString(), CACHE_TTL);
}

// Write-behind: update cache now, database later (RISKY)
public void writeBehind(String accountId, BigDecimal balance) {
    // Update cache immediately
    redis.opsForValue().set("balance:" + accountId,
        balance.toPlainString());

    // Async flush to database (if Redis crashes, data is lost)
    asyncExecutor.submit(() ->
        repository.updateBalance(accountId, balance));
}
TEXT
Write-through: slower writes, but cache and DB always agree.
Write-behind: fastest writes, but data loss risk on failure.
Cache-aside: best balance of simplicity, safety, and performance.

What is TTL and why is it a safety net?

TTL (Time To Live) automatically expires a cache entry after a set duration. Even if your invalidation logic has a bug, TTL ensures stale data is cleaned up eventually.

JAVA
// Set TTL when caching
redis.opsForValue().set("balance:SAV2001", "75000.00",
    Duration.ofSeconds(60));

// After 60 seconds, Redis automatically deletes the key.
// The next read triggers a cache miss and fetches fresh data.
TEXT
// Without TTL: if invalidation fails, stale data lives forever.
// With TTL of 60s: worst case, stale data lives for 60 seconds.

// Rule of thumb for banking:
// - Account balance: TTL 30-60 seconds
// - Customer profile: TTL 5-10 minutes
// - Branch list: TTL 1-24 hours
// - Exchange rates: TTL 5-15 minutes

Spring Cache supports TTL through the cache provider configuration:

JAVA
package com.bank.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import java.time.Duration;
import java.util.Map;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisCacheManager cacheManager(
            RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration defaults = RedisCacheConfiguration
            .defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(5))
            .disableCachingNullValues();

        Map<String, RedisCacheConfiguration> perCache = Map.of(
            "accounts",
            defaults.entryTtl(Duration.ofSeconds(60)),
            "branches",
            defaults.entryTtl(Duration.ofHours(1))
        );

        return RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(defaults)
            .withInitialCacheConfigurations(perCache)
            .build();
    }
}
TEXT
// Cache "accounts" entries expire after 60 seconds.
// Cache "branches" entries expire after 1 hour.
// All other caches use the default 5-minute TTL.

What is event-driven cache invalidation?

In a microservices architecture with multiple instances, a single instance deleting a Redis key does not invalidate local caches on other instances. Event-driven invalidation uses a message broker (Kafka) to notify all instances.

JAVA
package com.bank.service;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CacheInvalidationService {

    private final KafkaTemplate<String, String> kafka;
    private final StringRedisTemplate redis;

    public CacheInvalidationService(
            KafkaTemplate<String, String> kafka,
            StringRedisTemplate redis) {
        this.kafka = kafka;
        this.redis = redis;
    }

    // When account is updated, publish invalidation event
    public void publishInvalidation(String accountId) {
        kafka.send("cache-invalidation",
            accountId, "INVALIDATE:" + accountId);
    }

    // All instances listen and evict their local/Redis cache
    @KafkaListener(topics = "cache-invalidation",
        groupId = "${spring.application.name}")
    public void handleInvalidation(String message) {
        String accountId = message.replace("INVALIDATE:", "");
        redis.delete("balance:" + accountId);
        redis.delete("account:" + accountId);
    }
}
TEXT
// Flow:
// 1. Instance A updates account SAV2001 in the database.
// 2. Instance A publishes "INVALIDATE:SAV2001" to Kafka.
// 3. Instances A, B, C all consume the event.
// 4. All instances delete SAV2001 from their Redis cache.
// 5. Next read on any instance triggers a fresh DB query.

What are common mistakes with cache invalidation?

Mistake 1: Delete cache before database update

WRONG: Deleting the cache first, then updating the database.

JAVA
// WRONG: Race condition
public void updateBalance(String accountId, BigDecimal balance) {
    redis.delete("balance:" + accountId); // 1. Delete cache
    // Another thread reads here and re-caches the OLD value
    repository.updateBalance(accountId, balance); // 2. Update DB
    // Cache now has the OLD value permanently until TTL expires
}

CORRECT: Update the database first, then delete the cache.

JAVA
// CORRECT: DB first, cache second
public void updateBalance(String accountId, BigDecimal balance) {
    repository.updateBalance(accountId, balance); // 1. Update DB
    redis.delete("balance:" + accountId);         // 2. Delete cache
    // Next read fetches the new value from the database
}

Mistake 2: No TTL as a safety net

WRONG: Caching without TTL. If invalidation has a bug, stale data lives forever.

JAVA
// WRONG: No expiry
redis.opsForValue().set("balance:SAV2001", "75000.00");
// If invalidation fails, this value stays forever.

CORRECT: Always set a TTL.

JAVA
// CORRECT: TTL ensures stale data expires
redis.opsForValue().set("balance:SAV2001", "75000.00",
    Duration.ofSeconds(60));

What should a senior or principal engineer know?

- Cache stampede. When a popular key expires, hundreds of concurrent requests all miss the cache and hit the database simultaneously. Prevent this with a distributed lock: only one thread fetches from the database and repopulates the cache. Others wait.

- Stale-while-revalidate. Serve the stale cached value immediately while asynchronously refreshing it in the background. This provides low latency and near-fresh data. Implement by keeping a "soft TTL" in the cached value and refreshing asynchronously when the soft TTL expires but the hard TTL has not.

- Double delete. After updating the database and deleting the cache, a concurrent read might still populate the cache with old data from a slow database replica. Add a delayed second delete (for example, 500ms later) to handle this race.

- Cache warming on deployment. After a deployment or Redis restart, the cache is empty and all traffic hits the database. Pre-warm the cache by loading the most frequently accessed keys (top 1000 accounts) during startup.

- Observability. Monitor cache hit rate, miss rate, and eviction rate. A hit rate below 90% suggests the TTL is too short or the invalidation is too aggressive.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.locks.Lock;

@Service
public class StampedeProtectedCache {

    private final StringRedisTemplate redis;
    private final AccountRepository repository;
    private final org.redisson.api.RedissonClient redisson;

    public StampedeProtectedCache(StringRedisTemplate redis,
            AccountRepository repository,
            org.redisson.api.RedissonClient redisson) {
        this.redis = redis;
        this.repository = repository;
        this.redisson = redisson;
    }

    public BigDecimal getBalance(String accountId) {
        String key = "balance:" + accountId;
        String cached = redis.opsForValue().get(key);
        if (cached != null) {
            return new BigDecimal(cached);
        }

        // Distributed lock prevents stampede
        Lock lock = redisson.getLock("lock:balance:" + accountId);
        lock.lock();
        try {
            // Double-check after acquiring lock
            cached = redis.opsForValue().get(key);
            if (cached != null) {
                return new BigDecimal(cached);
            }

            BigDecimal balance = repository.findBalance(accountId);
            redis.opsForValue().set(key, balance.toPlainString(),
                Duration.ofSeconds(60));
            return balance;
        } finally {
            lock.unlock();
        }
    }
}
TEXT
// Cache stampede protection:
// 100 concurrent requests for SAV2001 balance
// Thread 1 acquires the lock, queries DB, populates cache
// Threads 2-100 wait, then read from cache
// Result: 1 DB query instead of 100

What are common interview follow-up questions?

  • What is the difference between cache-aside and write-through?
  • Why should you update the database before deleting the cache?
  • What is a cache stampede and how do you prevent it?
  • How do you handle cache invalidation across multiple microservice instances?
  • What is stale-while-revalidate and when do you use it?
  • How do you choose the right TTL for different data types?
  • What is the difference between @Cacheable, @CacheEvict, and @CachePut?
  • How do you pre-warm a cache after a deployment?

Visual Overview

TEXT
  Cache-Aside Pattern
  ====================

  READ:
  Client -> Check Redis Cache
              |
              +-- HIT  -> Return cached value
              |
              +-- MISS -> Query Database
                           |
                           v
                         Store in Redis (with TTL)
                           |
                           v
                         Return value to client

  WRITE:
  Client -> Update Database
              |
              v
            Delete Redis Cache Entry
              |
              v
            Next read triggers fresh DB query
TEXT
  Event-Driven Invalidation
  ==========================

  Instance A           Kafka              Instance B, C
  +---------+     +-------------+     +---------+
  | Update  | --> | cache-      | --> | Consume |
  | DB      |     | invalidation|     | event   |
  | Publish |     | topic       |     | Delete  |
  | event   |     +-------------+     | cache   |
  +---------+                         +---------+

Key Takeaway

Cache invalidation is the hardest part of caching, and it matters most in banking systems where stale data means incorrect balances and failed transfers. The safest default is cache-aside with TTL: read from cache first, fall back to the database on a miss, and populate the cache with a time limit. When data changes, update the database first, then delete the cache entry. The order matters because reversing it creates a race condition where stale data gets re-cached.

TTL is your safety net. Even if the invalidation logic has a bug, the cached entry expires after the configured duration. For account balances, 30-60 seconds is typical. For branch lists, an hour or more is fine. Always set a TTL. Never cache without one.

In a microservices environment, one instance deleting a Redis key is not enough. Other instances may have local caches or may have already started a read that will re-cache old data. Event-driven invalidation through Kafka ensures all instances receive the invalidation signal.

For production, protect against cache stampedes with distributed locks, use stale-while-revalidate for low-latency reads, and monitor cache hit rates. A hit rate below 90% is a warning sign that the TTL is too short or invalidation is too aggressive.

Remember one sentence: update the database first, delete the cache second, and always set a TTL.

---

Share
Use ← → arrow keys to navigate