Built‑in In‑Memory Cache vs. Spring Cache for Thymeleaf Fragment Caching: Which Is Better for Stale Data Prevention?
0 reputation · 05 Jan 2026, 07:45 UTC
0 reputation · 05 Jan 2026, 07:45 UTC
To determine the most reliable strategy for keeping Thymeleaf fragment data current in a multi‑node application.
The built‑in cache is single‑threaded and requires manual clearing; it offers no TTL or automatic invalidation. Spring Cache, while configurable with Redis or Hazelcast, introduces extra wiring and potential latency.
It is unclear which approach provides acceptable freshness without sacrificing performance or scalability in a clustered environment.
35275 reputation · 05 Jan 2026, 17:51 UTC
Spring Cache backed by a distributed store such as Redis or Hazelcast is the better choice for preventing stale Thymeleaf fragments in a multi-node application. Thymeleaf's built-in cache is per-JVM, single-threaded, has no TTL, and requires manual clearing, so it cannot invalidate entries across nodes.
When backing data changes on one node, other nodes may continue rendering the cached fragment from their own memory. Because the built-in cache has no cross-node invalidation, the stale fragment remains until that node is manually cleared or restarted.
Do you already operate Redis or Hazelcast in this cluster? If not, the recommendation shifts from adding Spring Cache with Redis to using Spring Cache with short local TTL plus application-level invalidation events, because introducing a distributed cache only for fragments may be disproportionate.
This assumes Thymeleaf 3.x with Spring Boot 3.x / Spring Framework 6.x and multiple JVM nodes behind a load balancer. No latency measurements are included; treat any specific millisecond figure as unverified until you benchmark your cache provider and fragment size.
spring.cache.type=redis
spring.cache.redis.time-to-live=60s
Confirm with a two-node test: request a fragment, update its data, wait for TTL or send an eviction, then request again on both nodes. Updated output on both nodes indicates cross-node freshness is working.
Use comments to ask for clarification. Post a solution as an answer.
35,275 reputation · 05 Jan 2026, 13:14 UTC
The built-in fragment cache lives inside the TemplateEngine instance as a JVM-local map. It has no TTL, LRU or automatic invalidation, so a fragment change is only visible after the engine is restarted or the cache is cleared manually on that node.
In a multi-node deployment that manual clear must be performed on every node. Missing one node leaves divergent fragment versions and persistent stale data that restarts alone will not resolve cluster-wide.