Implementing a Redis Cache-Aside Layer in Front of PostgreSQL with Spring Boot

Oct 18, 2026javaspring-bootredispostgresqlcachingbackend

Implementing a Redis Cache-Aside Layer in Front of PostgreSQL with Spring Boot

Most articles on “Redis + Spring Boot” show you a five-line @Cacheable annotation and call it a day. That’s fine once you understand what’s actually happening underneath — but I wanted to build the same thing twice: once by hand, wiring RedisTemplate calls myself, and once using Spring’s caching abstraction, so I could see exactly what the annotation was doing for me before I trusted it. This post walks through both, plus a couple of real bugs I hit along the way that are worth knowing about if you’re on a recent Spring Boot / Spring Data Redis version.

Why cache in front of a relational database at all

In a 3-tier app — client, application/business logic, data — Redis sits inside the application tier as a fast key-value layer that intercepts reads before they reach Postgres. The target use case is read-heavy data that’s relatively expensive to fetch (a query with joins, an aggregation, or just a hot row getting hammered) but doesn’t change every request. Instead of Postgres answering the same query over and over, the application checks Redis first; only on a miss does it fall through to the database, and it repopulates the cache before returning.

This is the cache-aside pattern, and it’s the one pattern worth understanding cold before anything else — write-through, write-behind, and the rest are variations on the same idea.

Architecture

Client
  |
  v
Spring Boot REST API  (application/business logic tier)
  |               \
  v                v
Redis (cache)     PostgreSQL (system of record)

Reads check Redis first and only fall through to Postgres on a miss. Writes go straight to Postgres and explicitly evict the corresponding Redis key, rather than trying to keep the cache updated in place — evict-on-write is simpler to reason about and harder to get subtly wrong than update-on-write.

Stack: Spring Boot (Java, Eclipse), Spring Data JPA, Spring Data Redis, PostgreSQL, Redis running in Docker locally. No frontend — the whole point of the exercise lived in the service layer, and REST endpoints were tested directly via Postman/curl.

The domain

A single Product entity (id, name, price as BigDecimal — never use floating point for money) with a standard ProductRepository extends JpaRepository<Product, Long> and a thin ProductController exposing GET /products/{id}, POST /products, and PUT /products/{id}.

Version 1: cache-aside by hand

Before reaching for @Cacheable, I implemented the pattern manually in the service layer, so the mechanics were fully visible:

@Service
public class ProductService {

    private static final String CACHE_PREFIX = "product:";
    private static final long TTL_MINUTES = 10;

    private final ProductRepository productRepository;
    private final RedisTemplate<String, Product> redisTemplate;

    public ProductService(ProductRepository productRepository, RedisTemplate<String, Product> redisTemplate) {
        this.productRepository = productRepository;
        this.redisTemplate = redisTemplate;
    }

    public Product getProductById(Long id) {
        String cacheKey = CACHE_PREFIX + id;

        Product cached = redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            System.out.println("Cache HIT: " + cacheKey);
            return cached;
        }

        System.out.println("Cache MISS: " + cacheKey);
        Product product = productRepository.findById(id).orElse(null);
        if (product != null) {
            redisTemplate.opsForValue().set(cacheKey, product, Expiration.from(Duration.ofMinutes(TTL_MINUTES)));
        }
        return product;
    }

    public Product updateProduct(Long id, Product updatedProduct) {
        return productRepository.findById(id)
                .map(existing -> {
                    existing.setName(updatedProduct.getName());
                    existing.setPrice(updatedProduct.getPrice());
                    Product saved = productRepository.save(existing);
                    redisTemplate.delete(CACHE_PREFIX + id);   // invalidate on write
                    return saved;
                })
                .orElse(null);
    }
}

Nothing exotic — check Redis, fall through to Postgres on a miss, populate Redis with a TTL, and explicitly delete the cache key whenever the underlying row changes.

A real bug: ClassCastException on cache reads

The first attempt at RedisConfig used a generic serializer meant to handle any object type:

template.setValueSerializer(GenericJacksonJsonRedisSerializer.builder().build());

This compiled fine, populated Redis fine — and then blew up on read with:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.example.demo.entity.Product

The root cause: the generic serializer doesn’t embed type metadata (a @class field) into the stored JSON by default — a deliberate security choice, since auto-reconstructing arbitrary classes from stored data is a known deserialization vulnerability pattern. Without that metadata, Jackson has no way to know a given blob of JSON should become a Product rather than a generic Map, so it defaults to LinkedHashMap.

The fix was to bind the serializer to the known type up front instead of trying to make it generic:

template.setValueSerializer(new JacksonJsonRedisSerializer<>(Product.class));

JacksonJsonRedisSerializer<T> knows the target type at construction time, so it never needs embedded metadata to deserialize correctly. This is also arguably the better design for a cache centered on one or two entity types — the generic “store anything” serializer is really meant for caches holding many unrelated object shapes.

Version 2: the same thing, declaratively

Once the manual version worked and I understood exactly what it was doing, the refactor to Spring’s caching annotations was mostly deletion:

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration productsCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10))
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new JacksonJsonRedisSerializer<>(Product.class)));

        return RedisCacheManager.builder(connectionFactory)
                .withCacheConfiguration("products", productsCacheConfig)
                .build();
    }
}
@Service
public class ProductService {

    private final ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        System.out.println("DB HIT (cache miss) for id: " + id);
        return productRepository.findById(id).orElse(null);
    }

    @CacheEvict(value = "products", key = "#id")
    public Product updateProduct(Long id, Product updatedProduct) {
        return productRepository.findById(id)
                .map(existing -> {
                    existing.setName(updatedProduct.getName());
                    existing.setPrice(updatedProduct.getPrice());
                    return productRepository.save(existing);
                })
                .orElse(null);
    }
}

Under the hood, @Cacheable works via a Spring AOP proxy wrapped around the ProductService bean. Any call routed through that proxy first checks the named cache ("products") for a key computed from the SpEL expression (#id); on a hit, it returns the cached value and the method body never executes at all — which is why the println only fires on a genuine miss. On a miss, the real method runs, and the proxy stores its return value before handing it back. The one gotcha worth knowing: this only works for calls that go through the proxy, so a method calling another @Cacheable method on this from inside the same class silently bypasses caching entirely — a classic Spring AOP pitfall.

The Redis key Spring actually creates is namespaced as products::1 (cache name + :: + your key) — visible directly with redis-cli KEYS "products*", which is a good way to confirm the annotation is doing what you think rather than taking it on faith.

Verifying it end to end

  1. GET /products/1 twice in a row — first call logs DB HIT (cache miss), second call logs nothing (served entirely from Redis).
  2. redis-cli GET products::1 — readable JSON, confirming the typed serializer is working.
  3. PUT /products/1 to change a field, then GET /products/1 again — should log a miss and return the updated value, proving the evict-on-write logic actually invalidates stale data rather than just existing in code.

Lessons learned

Building the manual version first, before reaching for the annotation, was worth the extra time — @Cacheable stopped being “magic” once I’d already written the check/miss/populate logic by hand. The ClassCastException bug was also a good forcing function: it’s the kind of thing that only shows up once you actually run the code, and understanding why it happened (no embedded type metadata by design, for security reasons) is a better interview answer than just pattern-matching a Stack Overflow fix. And separating writes-never-touch-cache from reads-check-cache-first turned out to be the one design decision worth being explicit about early — it’s easy to assume a cache is more automatically consistent than it actually is.