Video in progress

Middle 🌱 Spring

How does @RefreshScope work, and what are the limitations of updating a setting without restarting the application?

@RefreshScope (Spring Cloud) wraps the bean in a proxy. When /actuator/refresh is called, the Environment is re-read, such beans are discarded, and they're recreated with the new value on the next call. It works per instance and doesn't suit every bean.

📖 Answer

@Service
@RefreshScope
class DiscountPolicy {
    private final BigDecimal rate;

    DiscountPolicy(@Value("${shop.discount-rate}") BigDecimal rate) {
        this.rate = rate;
    }
}

The sequence:

  1. A value changed in the Config Server (or a Kubernetes ConfigMap).
  2. POST /actuator/refresh is called: Spring Cloud loads the new Environment and returns the list of changed keys.
  3. The @RefreshScope beans are discarded. Whoever injected them is really holding a proxy, so on the next method call the bean is recreated with the new value.
  4. @ConfigurationProperties beans are rebound through EnvironmentChangeEvent even without @RefreshScope.

The limitations:

  • it's per instance: with 10 pods you'd have to call refresh 10 times. Spring Cloud Bus (through Kafka/RabbitMQ) or Kubernetes integration automates this;
  • stateful beans: refreshing a DataSource, connection pool or thread pool drops connections or leaves a half-applied state. For such settings a restart is safer;
  • @Value in an ordinary singleton isn't updated, because the value was read once at creation;
  • brief inconsistency: during a refresh some pods work with the old value and some with the new;
  • leaving the /actuator/refresh endpoint open is a security hole, so protect it.

In practice: refresh is convenient for simple, frequently changing values like feature flags and limits. For an infrastructure setting, a rolling restart is simpler and more reliable.