Video in progress
How does `@RefreshScope` update configuration without a restart, and what problems can it cause?
@RefreshScope beans are served through a proxy; after a refresh event the cached bean is discarded and recreated with the new configuration on the next call. The problems: intermediate states, loss of state inside the bean, and pods being updated at different times.
📖 Answer
In Spring Cloud, when /actuator/refresh is called (or a message arrives through Spring Cloud Bus), the Environment is re-read. @ConfigurationProperties beans are rebound, and @RefreshScope beans are removed from the scope cache. What's injected into others is actually a proxy, so the next method call creates a new instance.
@RefreshScope
@Component
class DiscountPolicy {
@Value("${discount.max-percent}")
private int maxPercent;
}
Problems seen in practice:
- Expensive beans. Putting a
DataSourceor an HTTP client in refresh scope means the pool is recreated on refresh, and old connections may be left hanging. - State is lost. If a bean has a cache or counter inside, it resets to zero.
- A mixed state within one request. If a refresh happens in the middle of a request, part of it sees the old value and part the new one.
- Pods aren't in sync. With 10 pods, if the refresh reached 7 of them, for a short time the same request gets different answers depending on the pod.
- Kubernetes ConfigMap. When mounted as a file, an update can be delayed by up to a minute, and environment variables aren't updated at all; you need to restart the pod.
So I use refresh only for simple values like feature flags, limits and texts. For infrastructure settings (pool size, URL), a rolling restart is more reliable and predictable.
Sign up to mark studied questions and save your progress.