Imagine a fictional payment company operating 8,000 service instances across three regions. An engineer changes the checkout timeout from two seconds to 200 milliseconds. Within minutes, healthy payments start failing because every instance receives the same incorrect setting. Restarting thousands of processes is slow, and nobody knows which instances have loaded the change. A distributed configuration service solves this operational problem, but only if it treats configuration changes as controlled deployments rather than ordinary database updates.

What you will learn
- Version and validate configuration
- Design reliable distribution and local caching
- Implement staged rollout and rollback
- Handle partitions, stale clients and audit requirements
Difficulty: Advanced | Prerequisites: HTTP APIs, distributed consistency, caching and basic deployment pipelines.
Table of contents
- Requirements and scale
- Architecture evolution
- API and storage
- Rollout and rollback
- Reliability and security
- Testing and interview practice
- Frequently asked questions
Requirements and scale
Functional requirements
- Create immutable configuration versions
- Validate schema and approve changes
- Roll out to selected environments and cohorts
- Watch or fetch desired configuration
- Report applied revision and roll back
Non-functional requirements
- Durable ordered revisions per scope
- Low latency local configuration reads
- Bounded propagation under healthy conditions
- Tenant isolation and complete audit history
- Continued service during control-plane outages
Define a scope as tenant, environment and service. A scope owns a complete configuration snapshot, not an arbitrary collection of independent mutable keys. Atomic snapshots prevent a client from observing a new endpoint paired with an old credential reference. Cross-service changes are explicitly outside the single-scope atomicity guarantee; coordinate them through compatible schemas and staged migrations.
| Planning assumption | Estimate | Implication |
|---|---|---|
| 8,000 agents polling every 30 seconds | 267 requests/s average | Add jitter and conditional requests |
| 100 KB per snapshot | 800 MB for fleet-wide update | Use regional caches and staggered rollout |
| 500 scopes × 20 revisions/day | 10,000 revisions/day | About 1 GB/day raw snapshot storage |
| 30-day raw retention | 30 GB | Exclude replication, metadata and compression |
These are hypothetical estimates, not measurements from a real company. A synchronized restart can create 8,000 concurrent fetches, far exceeding the average. Design for burst recovery as well as steady state. The data plane should read an in-process snapshot without a network round trip for each business request.
Architecture evolution
Stage 1: Configuration files
Local files are simple, reproducible and easy to review in Git. However, applying a change often requires deployment or restart. Drift appears when operators manually modify instances.
Stage 2: Central API
A central store provides version history and remote updates. Polling makes distribution straightforward, but a naive implementation creates synchronized load and unsafe fleet-wide changes.
Stage 3 introduces a control plane for proposals, approval, rollout and auditing, plus a distribution plane optimized for immutable snapshot retrieval. The control plane publishes desired revisions; agents independently fetch and apply them. This separation allows existing applications to continue serving requests when operators cannot publish new changes.
| Component | Responsibility |
|---|---|
| Admin API | Authentication, proposals, approval and optimistic concurrency |
| Validator | Schema, policy and semantic checks |
| Version store | Immutable content and monotonically increasing desired revisions |
| Rollout controller | Cohorts, health gates, pause and rollback |
| Regional distribution API | Conditional fetch and watch notifications |
| Client agent | Verify, validate, atomically apply and persist last-known-good snapshot |
| Telemetry and audit | Applied revisions, health signals and change history |
An operator submits a candidate. Validation checks the schema and domain rules, then an authorized reviewer approves the change. The controller assigns a desired revision to a small stable cohort. Agents receive a notification, fetch the immutable snapshot, verify its digest and atomically replace the local reference. They report the applied revision and health metrics. The controller expands only when the observation window and health criteria are satisfied.
Treat configuration as a deployment: version it, validate it, observe it and make rollback routine.
API contracts and storage model
| Endpoint | Purpose |
|---|---|
| POST /scopes/{scope}/versions | Create validated immutable candidate |
| POST /scopes/{scope}/rollouts | Start approved rollout with expected revision |
| GET /scopes/{scope}/desired | Fetch cohort-specific desired revision |
| GET /versions/{id} | Fetch immutable authorized snapshot |
| POST /agents/{id}/status | Report applied revision and error |
| POST /rollouts/{id}/rollback | Create new desired revision referencing previous content |
POST /scopes/payments-prod/rollouts
If-Match: "revision-41"
Idempotency-Key: rollout-202
{"version_id":"v82","canary_percent":5}
202 Accepted
{"rollout_id":"r202","state":"CANARY","revision":42}
The If-Match precondition prevents an operator from unknowingly overwriting a newer desired state. An idempotency key handles lost responses; bind it to caller, scope and request hash. Return 412 for a stale precondition, 409 for conflicting active rollout, 422 for invalid configuration and 403 for insufficient authorization. Agent fetches use ETag and If-None-Match to avoid transferring unchanged snapshots.
CREATE TABLE config_versions (
scope_id text NOT NULL,
version_id uuid NOT NULL,
content jsonb NOT NULL,
digest text NOT NULL,
schema_version integer NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (scope_id, version_id)
);
CREATE TABLE desired_config (
scope_id text PRIMARY KEY,
revision bigint NOT NULL,
version_id uuid NOT NULL,
FOREIGN KEY (scope_id, version_id)
REFERENCES config_versions(scope_id, version_id)
);
Store rollout state, cohort assignments and append-only audit events separately. A production schema also needs tenant-aware authorization, actor identity, approval records and unique idempotency keys. For larger snapshots, store immutable content in object storage and commit its digest and location only after successful upload. Garbage collection must retain any version referenced by active rollouts, desired pointers or retention policy.
UPDATE desired_config
SET revision = revision + 1, version_id = :candidate
WHERE scope_id = :scope AND revision = :expected
RETURNING revision;
Zero updated rows means the expected revision is stale. Commit the desired pointer and its outbox event together. The relay may publish notifications more than once, so agents treat notifications as hints and fetch the current authorized desired state. A missed notification is repaired by periodic polling.
Safe rollout and rollback
A canary cohort should be deterministic and representative. Hash a stable agent identity together with the scope, then select a percentage of the hash space. Stratify by region or workload class when necessary. Randomly choosing a new cohort every polling interval makes health attribution unreliable.
| Phase | Example policy | Action on failure |
|---|---|---|
| Validation | Schema, bounds, dependency checks | Reject candidate |
| Canary | 5% for at least 10 minutes | Pause or rollback |
| Expansion | 25%, then 50% | Evaluate health at each gate |
| Completion | 100% desired; track acknowledgments | Investigate stragglers |
These percentages and durations are illustrative. A low-volume service may need a longer observation window to collect enough requests. Compare canary error rate and latency against a comparable control cohort, enforce absolute safety thresholds, and treat missing telemetry as insufficient evidence to expand. Require an operator override with audit logging for exceptional situations.
Critical distinction: version versus revision
Version identifies immutable content. Revision identifies the order of desired-state decisions. Rolling back revision 42 to content from revision 41 creates revision 43 referencing the older content. Agents must not reject rollback simply because its content version is older.
def refresh(agent):
desired = fetch_desired(agent.scope, agent.identity)
if desired.revision <= agent.applied_revision:
return
raw = fetch_authorized_snapshot(desired.version_id)
verify_digest(raw, desired.digest)
candidate = validate_and_build(raw)
with agent.apply_lock:
if desired.revision <= agent.applied_revision:
return
persist_snapshot_atomically(candidate, desired.revision)
agent.swap_snapshot(candidate, desired.revision)
report_applied(agent.identity, desired.revision)
This is illustrative pseudocode, not a complete SDK. The lock prevents an older concurrent refresh from overwriting a newer snapshot. Persist the snapshot and revision as a single durable record using an atomic rename or local transaction; on startup validate that record before serving. A crash after persistence but before the in-memory swap is repaired by loading the persisted snapshot on restart. Report acknowledgment only after successful application. Configuration that requires connection recreation or restart needs a specialized application adapter rather than a simple pointer swap.
Reliability, scaling and security
Control plane
Use strongly consistent writes for desired-state decisions. During leader loss, reject conflicting changes until a new leader is established. Partition scopes to spread write load.
Distribution plane
Serve immutable snapshots through regional caches. Watch streams reduce normal propagation latency; jittered polling repairs missed events and disconnected streams.
| Failure | Expected behavior |
|---|---|
| Control plane unavailable | Continue using last-known-good configuration |
| Watch notification lost | Periodic fetch discovers desired revision |
| Invalid candidate | Reject locally and report failure |
| Regional cache stale | Revalidate desired metadata; immutable content remains safe |
| Controller crashes | Resume durable rollout state with fenced ownership |
| Canary error spike | Pause expansion and create rollback revision |
| Agent offline | Apply current desired revision when reconnecting |
A last-known-good cache is not a universal fail-open policy. For ordinary tuning parameters, stale configuration may be acceptable for hours. For security revocation, emergency disable switches or expiring credentials, define a maximum staleness and explicit fail-closed or degraded behavior. Track freshness independently from application availability.
Use mutual TLS or workload identity for agents, scope-based authorization for fetches, and separate proposal and approval roles for sensitive production changes. Do not embed raw secrets in general configuration snapshots; store references to a secret manager and use separately authorized retrieval. Encrypt stored configuration, redact sensitive values from logs and audit changes with actor, scope, revision and timestamp.
| Distribution approach | Strength | Tradeoff |
|---|---|---|
| Polling | Simple and robust | Propagation delay and recurring load |
| Long polling / watch | Fast notification | Connection management and reconnect storms |
| Push full snapshot | Low fetch overhead | Backpressure and delivery complexity |
| Watch plus immutable fetch | Efficient recovery and cacheability | Two-stage protocol |
For multi-region operation, keep one authoritative writer per scope or use a consensus-backed store. Regional readers may lag, so expose desired revision and freshness. During partitions, preserve existing snapshots and avoid accepting independent conflicting desired-state writes. A disaster recovery exercise should restore version history, desired pointers and audit records together; verify referenced objects still exist before reopening changes.
Testing, observability and interview practice
- Unit: validate schema boundaries, digest mismatch, cohort stability and revision ordering.
- Integration: simulate duplicate rollout requests, stale If-Match and atomic outbox writes.
- Contract: verify old agents can reject or safely interpret newer schemas.
- Concurrency: deliver revision 43 before 42 and assert revision 42 cannot overwrite it.
- Resilience: disconnect watch streams, kill controller during expansion, corrupt local cache and restore from backup.
- Load: restart thousands of agents simultaneously; measure jitter, cache hit rate and origin saturation.
Monitor desired-to-applied revision lag by region, percentage of agents on each revision, validation rejection rate, rollout duration, stale-agent count, fetch latency, cache hit rate and control-plane write conflicts. Alert on stalled rollouts and health regressions, not merely on the presence of a running controller. Define a propagation SLO only for connected healthy agents, and report disconnected agents separately so the metric cannot hide failures.
Interview tip
Start by distinguishing configuration from secrets and feature flags. Explain immutable snapshots and revision ordering before introducing Kafka, Redis or consensus. A strong senior-level answer shows how the system behaves when a rollout fails halfway through.
Practice exercise: build a small Python agent and PostgreSQL-backed desired-state API. Launch 100 simulated agents, roll out a deliberately invalid timeout to five agents, then roll back using a new revision. Assert that unaffected agents retain their original snapshot and that all canary agents converge to the rollback revision. Extend the exercise with a lost notification and a process crash between persistence and acknowledgment.
Frequently asked questions
Why not store every configuration key independently?
Independent key updates can expose inconsistent combinations. A snapshot makes related settings atomic within a scope. Independent keys can still be useful when they have genuinely independent lifecycles, but the system must explicitly define its consistency boundary.
Does every agent need to acknowledge before rollout completes?
Not necessarily. Define a healthy connected cohort and a convergence threshold, then track offline agents separately. For critical changes, require stronger acknowledgment or enforce a freshness policy. Never interpret silence as proof of successful application.
Can Git be the configuration source of truth?
Yes. Git offers review and immutable history, but runtime distribution still needs a controller that maps approved commits to ordered desired revisions, validates artifacts and reports applied state. Git alone does not establish that every running process has applied a change.
How is rollback different from reverting a database transaction?
Rollback is a new distributed deployment of previous content. Some agents may already have applied the bad configuration and external side effects may not be reversible. The controller must converge agents to a new revision and separately address any irreversible effects.
How do you handle incompatible schema changes?
Use backward-compatible additions, explicit schema versions and capability reporting. Deploy consumers that understand both old and new representations before enabling the new configuration. Reject incompatible snapshots locally rather than silently interpreting them.
Should the service fetch configuration on every request?
Normally no. Business requests should read an immutable local snapshot. Network fetches happen asynchronously, which avoids adding a control-plane dependency to the request path. Critical freshness requirements can be enforced using local age checks.
Conclusion and further reading
A reliable configuration platform is a deployment system with a fast distribution layer. Start with immutable snapshots, ordered desired revisions, atomic local application and an audit trail. Add staged rollout and health gates before optimizing watch latency. The central design principle is to keep the business data plane operational while configuration changes remain controlled, observable and reversible where possible.
- etcd documentation — consensus-backed storage and watches.
- Kubernetes ConfigMaps — documented configuration distribution behavior.
- Related tutorial: Distributed Notification System — reliable event delivery and retries.