Spring Cloud Config Client
👉 Understand how Spring Cloud Config Client retrieves and applies externalized configuration.
What is config client ?
Spring Cloud Config Client is a library that enables a Spring Boot microservice to fetch its configuration from a centralized Config Server at startup instead of relying solely on local property/config files.
It serves as the consumer-side component of centralized configuration management in a Spring Cloud-based microservice architecture that connects microservices to an externalized configuration source, ensuring consistent property management across the fleet.
Why config client exists ?
In distributed systems, managing configuration inside each individual service becomes unmanageable and error-prone as the number of microservices grows.
Manual updates lead to configuration drift and require risky re-deployments of the service even for simple value changes.
By externalizing configuration, services become environment-aware without being environment-dependent.
Spring Cloud Config Client exists to solve these architectural challenges:
- Externalizes configuration to decouple environment settings from the application code.
- Reduces redeployment cycles by allowing configuration updates without rebuilding JAR (app binary) files.
- Ensures consistency by providing a single “source of truth” for shared properties.
- Enables environment awareness, allowing the same binary to run in Dev, QA, or Prod.
When to use config client ?
Spring Cloud Config Client is essential for distributed systems where configuration must be governed centrally.
It is the preferred choice when multiple instances of a service must share identical settings or when security policies require secrets to be stored outside the application repository.
Spring Cloud Config Client should be used when:
- Multiple microservices share environment-specific configuration.
- Configuration must change without rebuilding artifacts.
- Consistency across service instances is critical.
- Teams want centralized governance of configuration values.
Insight:
It is especially effective when combined with Spring Cloud Config Server in multi-environment setups.
How config client fits into spring ecosystem ?
The Config Client operates during the bootstrap phase, contacting the Config Server before the main application context is fully initialized.
This ensures that all beans, including database connections and security filters, are configured with the correct values from the start.
The interaction flow is:
flowchart LR
A[Spring Boot Service<br/><br/>Application Start]
B[Spring Cloud Config Client<br/><br/>Bootstrap Phase]
C[Spring Cloud Config Server]
D[External Config Repository<br/><br/>Git / Versioned Store]
E[Spring Environment<br/><br/>Property Sources]
F[Spring ApplicationContext<br/><br/>Bean Initialization]
A --> B
B -->|Request config<br/>app name + profile| C
C -->|Fetch config| D
D -->|Return properties| C
C -->|Resolved configuration| B
B -->|Merge properties| E
E --> F
Request flow
Below sequence diagram demonstrates the flow of Spring Cloud Config Client fetching configuration from Config Server.
sequenceDiagram
autonumber
participant Client as Microservice (Client)
participant Server as Config Server
participant Git as Git Repository/Vault
Note over Client: 1. Service Start (Main Class)
rect rgb(240, 248, 255)
Note right of Client: Bootstrap Phase
Client->>Client: Initialize Bootstrap Context
Client->>Client: Resolve 'spring.application.name'
Client->>Server: HTTP GET /service-name/profile
end
activate Server
Server->>Git: Fetch properties for {app}-{profile}.yml
Git-->>Server: Return YAML/Properties
Server->>Server: Process & Merge Property Sources
Server-->>Client: Return JSON PropertySource
deactivate Server
rect rgb(245, 245, 245)
Note right of Client: Application Context Phase
Client->>Client: Merge remote properties into Environment
Client->>Client: Initialize Beans (@Value, @ConfigurationProperties)
Client->>Client: Fully Started
end
Developing config client app
Building a Spring Cloud Config Client involves adding the necessary starter dependency and defining the location of the Config Server. This process transforms a standard Spring Boot application into a configuration-aware microservice.
Enabling the config client
To enable Config Client behavior, include the Spring Cloud Config starter in your build file. This dependency triggers the auto-configuration logic required to communicate with the remote server.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Application configuration
The application.properties (or application.yml) file must specify the Config Server URL (where the configs are hosted and the name to identify app/service specific config to fetch.
Using the 'optional:` prefix is a best practice to allow the service to start even if the server is temporarily unreachable.
# Active profile
spring.cloud.config.profile=dev
# Service name used for lookup
spring.cloud.config.name=limits-service
# Config Server location
spring.config.import=optional:configserver:http://localhost:8888/
# Local fallback values (lowest priority)
limits-service.minimum=20
limits-service.maximum=21
Insight:
Remote configuration overrides local values unless explicitly disabled.
Property import mechanism (Spring Boot 2.4+)
`spring.config.import` is the standard property used by Spring Boot applications to specify and load configuration from external sources like a Spring Cloud Config Server.
This mechanism, introduced in Spring Boot 2.4, simplifies the bootstrap process by allowing applications to resolve remote properties directly within the standard application.yml or application.properties files.
Key behaviors of the Import mechanism
The transition to the import-based model, changed how applications react to the presence or absence of a Config Server. Understanding these behaviors is critical for designing resilient startup sequences in production environments.
Below points outline the functional characteristics of the `spring.config.import` property:
- “optional:” Prefix:
- Adding this prefix allows the application to continue starting even if the Config Server is offline or unreachable.
- Strict Dependency:
- Removing the `optional:` prefix forces the application to fail fast if it cannot establish a connection to the configuration source.
- Priority Precedence:
- Values defined via the import location take precedence over the legacy `spring.cloud.config.uri` property.
- Multiple Fetch Events:
- It is normal to observe multiple fetch requests during startup as Spring Boot resolves and activates specific profiles.
Legacy Bootstrap vs. modern Import
TBelow is the architectural shift in how Spring Cloud Config Clients connect to the server across different Spring Boot versions.
| Feature | Legacy Approach (Pre-2.4) | Modern Approach (2.4+) |
|---|---|---|
| Primary File | bootstrap.yml or bootstrap.properties | application.yml or application.properties |
| Configuration Key | spring.cloud.config.uri | spring.config.import |
| Startup Behavior | Required spring-cloud-starter-bootstrap | Native support in Spring Boot |
| Flexibility | Less control over property ordering | Fine-grained control over import priority |
Defining configuration binding
The client maps external properties to strongly-typed Java beans using the @ConfigurationProperties annotation. This approach provides type safety and makes configuration easier to inject into service logic.
@ConfigurationProperties(prefix = "limits-service")
@Component
public class LimitsServiceConfiguration {
private int minimum;
private int maximum;
// getters and setters
}
Insight:
This class maps external properties from config server having the prefix limits-service.*.
Consuming config in the service layer
Once bound, the configuration bean is injected into controllers or services via standard dependency injection.
This keeps the business logic isolated from the configuration source, as the controller only interacts with a local Java object.
@RestController
public class LimitsServiceController {
@Autowired
LimitsServiceConfiguration config;
@GetMapping("/limits")
public Limits retrieveLimits() {
return new Limits(config.getMinimum(), config.getMaximum());
}
}
Project Reference:
Refer the POC application for building a cloud client app Spring Cloud POC App - Config Client
Config client vs local config
Here’s the comparison of Spring Cloud Config Client with local configuration files to clarify when centralized configuration becomes necessary in distributed systems.
| Aspect | Local Configuration (application.properties / yml) | Spring Cloud Config Client |
|---|---|---|
| Definition | Configuration is packaged and managed inside each service binary. | Configuration is fetched dynamically from a centralized Config Server at startup. |
| Primary Purpose | Simple, self-contained configuration for single or small services. | Centralized, consistent configuration management across microservices. |
| Configuration Location | Inside the service repository and artifact. | External repository (Git, Vault, etc.) managed by Config Server. |
| Environment Separation | Achieved via multiple files or profiles inside each service. | Achieved centrally using profiles and environment-specific config files. |
| Consistency Across Services | Hard to guarantee; values can drift over time. | Enforced centrally; shared values remain consistent. |
| Change Management | Requires rebuilding and redeploying the service. | Changes can be applied without rebuilding artifacts. |
| Operational Overhead | Low initially, increases with service count. | Slightly higher setup cost, lower long-term maintenance. |
| Scalability | Poor for large systems with many services. | Designed for scalable microservice ecosystems. |
| Failure Impact | No external dependency during startup. | Depends on Config Server availability (can be optional). |
| Recommended Usage Stage | Early development or small monolithic-style services. | Production-grade microservices and multi-environment systems. |
| Security | Secrets often exposed in code | Secrets stored in secure vaults |
Configuration refresh strategies
Configuration refresh refers to the mechanism of updating property values in a running application without performing a full process restart.
Spring Cloud provides multiple strategies to handle these updates, ranging from manual triggers to automated events.
The table below summarizes the available strategies for propagating configuration changes in Spring Cloud, highlighting predictability, operational impact, and recommended usage.
| Strategy | How It Works | Primary Use Case | Advantages | Usage |
|---|---|---|---|---|
| Restart-Based Refresh | Service instances are restarted after configuration changes, forcing a fresh configuration fetch at startup. | Applying configuration changes safely in production environments. | Predictable behavior, clean application state, easy rollback, no runtime side effects. | Default and recommended approach for production systems. |
| Actuator-Based Manual Refresh | An external call triggers /actuator/refresh, updating beans marked with @RefreshScope. | Operational tuning and non-critical runtime adjustments. | No restart required, faster propagation than redeployments. | Use sparingly for safe, operational parameters only. |
| Spring Cloud Bus (Event-Driven) | A refresh event is broadcast via a message broker to all instances simultaneously. | Large-scale environments requiring coordinated refresh across many services. | Fast, centralized propagation, minimal manual effort. | Advanced platforms with strong governance and observability. |
Insight:
→Restart-based refresh prioritizes stability and predictability, making it the safest default choice.
→Runtime refresh strategies improve speed but introduce operational and behavioral risk, and should only be adopted with clear boundaries and discipline.
Config property resolution order
Property Resolution Order is the strict hierarchy Spring Boot follows to determine which value takes precedence when the same configuration key is defined in multiple locations.
In a Spring Cloud environment, remote properties fetched from the Config Server are designed to override local properties, ensuring centralized control.
This allows developers to define broad defaults locally while providing environment-specific overrides remotely.
The resolution behavior follows this descending priority:
- Remote Configuration:
- Properties fetched from the Config Server (e.g.,
application-prod.yml).
- Properties fetched from the Config Server (e.g.,
- Local Profile Configuration:
- Local files specific to a profile (e.g.,
application-dev.yml).
- Local files specific to a profile (e.g.,
- Local Default Configuration:
- The standard
application.ymlorapplication.properties.
- The standard
- Framework Defaults:
- Hardcoded values within the Spring Boot starters.
Architectural Note:
Local configuration should be treated as a safe fallback. It ensures the application can boot with “sane defaults” even if the Config Server is temporarily unavailable during an optional import.
Startup and runtime impacts
The following table details how different connectivity issues affect service availability based on the configuration of the `spring.config.import` property.
| Scenario | Config Import Mode | Service Startup | Runtime Impact |
|---|---|---|---|
| Config Server unreachable | Mandatory | ❌ Fails | Context fails to initialize. |
| Config Server unreachable | Optional | ✅ Starts | Uses local application.yml fallbacks. |
| Server crashes after startup | Any | ✅ Running | No immediate impact; existing beans are unaffected. |
| High network latency | Optional | ⚠️ Delayed | Startup time increases while waiting for timeout. |
| Malformed/Partial Response | Mandatory | ❌ Fails | Application fails during property binding. |
Summary:
→Using theoptional:prefix prioritizes availability, allowing services to start with local defaults.
→While the mandatory mode prioritizes consistency, preventing services from running with potentially stale or incorrect data.
Security boundaries
Spring Cloud Config Security Boundaries define the logical separation between operational application settings and sensitive credentials.
In a production-grade architecture, Spring Cloud Config acts as a distribution mechanism for behavior-altering properties, while dedicated systems like HashiCorp Vault or AWS Secrets Manager handle identity and access materials.
Why security boundaries matter ?
Centralizing configuration simplifies management but creates a “single point of failure”.
For security, if boundaries are blurred, without a clear distinction between settings and secrets, organizations face systemic risks.
- Source Control Exposure:
- Committing passwords to Git repositories makes them visible to anyone with read access.
- Leakage via Endpoints:
- Standard Spring Boot Actuator endpoints (like
/env) can expose raw configuration values if not properly secured.
- Standard Spring Boot Actuator endpoints (like
- Audit Deficiencies:
- Traditional Git histories rarely meet the compliance requirements for secret access auditing and rotation.
- Static Credentials:
- Managing secrets in configuration files makes automated rotation and short-lived credentials nearly impossible to implement.
Configuration types: Safe vs. Sensitive
To maintain a secure posture, architects must categorize every property before deciding where it resides.
Follow below outlines to distinguish between Safe Configuration and Sensitive Secrets.
| Property Type | Managed By | Examples | Risk Level |
|---|---|---|---|
| Operational Behavior | Spring Cloud Config | Feature flags, timeouts, thread pool sizes | Low |
| Environment Metadata | Spring Cloud Config | Service URLs, profile names, region identifiers | Low |
| Identity & Access | Secrets Manager / Vault | DB passwords, API keys, SSH private keys | Critical |
| Cryptographic Material | Secrets Manager / Vault | JWT signing keys, TLS certificates, salt values | Critical |
Note:
→Architectural Rule: If a property allows access to data or infrastructure, it is a secret and stays out of Spring Cloud Config.
Why it’s not a secrets manager ?
While it is technically possible to store secrets in Config Server, it is architecturally discouraged.
Spring Cloud Config is designed primarily for configuration distribution and versioning. While highly effective for application settings, it lacks the specialized security primitives required to function as a robust secrets manager.
The table below outlines the specific limitations that necessitate the use of a dedicated secret management system (like HashiCorp Vault or AWS Secrets Manager) for sensitive data.
| Limitation Category | Operational Reality | Security Impact |
|---|---|---|
| Data Visibility | Properties in Git-backed stores are often unencrypted at rest and visible to any developer with repository access. | Increases the risk of accidental credential exposure and insider threats. |
| Access Control | Config Server lacks granular RBAC; it cannot easily restrict access to specific keys on a per-user or per-service basis. | Violates the Principle of Least Privilege, as services often see more data than they require. |
| Serialization Risks | Secrets fetched as standard properties can be accidentally logged during startup or exposed via Actuator endpoints. | Credentials can leak into log aggregation systems (ELK/Splunk) or diagnostic reports. |
| Lifecycle & Rotation | It does not support native secret rotation, automated expiration, or the generation of dynamic credentials. | Forces the use of long-lived “static” secrets, which are harder to revoke if compromised. |
Secure configuration architecture
To move from a basic setup to a production-ready environment, you must implement a Separation of Concerns model.
This architecture treats Spring Cloud Config as a distribution engine for application behavior, while offloading sensitive data to specialized security systems.
Comparison of secure configuration patterns
Below patterns represent the standard for modern microservices. Choosing the right one depends on your infrastructure maturity and compliance needs.
| Pattern | Mechanism | Best Use Case | Risk Mitigation |
|---|---|---|---|
| Indirect References | Config Server stores a URI; App fetches secret from Vault at runtime. | Zero-Trust Environments | Prevents secrets from ever touching Git or the Config Server. |
| Platform Injection | Secrets injected via K8s Secrets/Env Variables during Pod startup. | Cloud-Native / Kubernetes | Centralizes identity management within the orchestration layer. |
| Property Encryption | Sensitive values are stored as {cipher}A1B2... in Git. | Legacy Migration | Protects values in Git, but relies on a shared key in the Config Server. |
Critical security Anti-patterns
Avoid these common “shortcuts” that introduce systemic vulnerabilities into your distributed system.
| Anti-Pattern | Why it is Dangerous | Standard Fix |
|---|---|---|
| Plain-text Git Secrets | Any developer or system with repo access can see production credentials. | Use git-crypt or move secrets to a dedicated Vault. |
| Universal Read Access | A single compromised service can read the DB passwords of the entire fleet. | Implement Config Server Profiles with specific access tokens. |
| Logging Environment | Debugging logs often capture and leak the entire Environment object. | Use Log Masking or exclude sensitive prefixes from log outputs. |
| Local Decryption Keys | Storing the decryption key inside the application JAR file. | Use Asymmetric Encryption (RSA) where only the server holds the private key. |
Design guidelines for secure configuration
Adopt a “Secure by Design” approach using these non-negotiable guidelines for 2025 deployments:
- Treat Config as Public:
- Architect your system assuming any value in your Config Server might be exposed; strictly limit it to non-sensitive data.
- Externalize Secret Lifecycle:
- Use a dedicated system (Vault/AWS/Azure Secrets) to handle the creation, rotation, and audit logs of secrets.
- Principle of Least Privilege:
- Configure each client service to only fetch the specific file/profile required for its operation.
- Audit Endpoints:
- Actively monitor and secure the `/configprops` and `/env` Actuator endpoints using Spring Security.
Production readiness checklist
Use the checklist below before promoting to production.
| Area | Checklist Item | Status |
|---|---|---|
| Availability | Multiple Config Server instances deployed | ☐ |
| Availability | Client uses optional:configserver: where appropriate | ☐ |
| Backing Store | Configuration repository highly available | ☐ |
| Security | No secrets stored in config repositories | ☐ |
| Security | Config Server access is restricted | ☐ |
| Profiles | Profile naming consistent across services | ☐ |
| Overrides | Local config used only as fallback | ☐ |
| Monitoring | Config Server health is monitored | ☐ |
| Monitoring | Client-side fetch failures are visible | ☐ |
| Change Mgmt | Config changes are version-controlled | ☐ |
| Operations | Restart strategy documented and tested | ☐ |