etcd compaction and defragmentation: why the database fills up on long-running clusters
When a long-running Kubernetes cluster starts returning an etcd alarm, or API writes slow down without an obvious cause, the first question is usually why the etcd database keeps growing when the workloads have not changed much. etcd does not overwrite a key in place. Every write creates a new revision, and etcd keeps the history of earlier revisions so that watchers and clients can read consistent past state. Over months, controllers that update status fields, leader elections, lease renewals and object churn add up to a large store full of old revisions. Compaction is the step that discards revisions older than a chosen point, and defragmentation is the separate step that returns the disk space freed by compaction to the file system. Compaction alone marks space as reusable inside the database file, so the file on disk often stays the same size until defragmentation runs.
Teams need this work when the cluster has been running for a long time without a deliberate maintenance plan, when the etcd database size approaches the configured space quota, or when etcdctl endpoint status shows a database size far larger than the live data would suggest. The space quota alarm is the point where etcd stops accepting writes to protect itself, and the cluster reports the cluster as in a NOSPACE condition. Recovering from that state is delicate, because the API server needs writes to succeed before most normal repair steps can run. Before changing anything, confirm the current database size on every member, the quota configured for the cluster, whether automatic compaction is already enabled and at what retention window, and whether a recent snapshot exists. Those values come from your own cluster and your distribution's defaults, so check them there rather than assuming them.
This page covers how automatic compaction is configured, how to schedule defragmentation without disrupting the leader, how the space quota alarm behaves, and the steps for clearing NOSPACE while keeping the control plane available. It also covers the checks to run before and after each step and when to stop and restore from a snapshot instead. Defragmentation is a blocking operation on each member that temporarily affects its responsiveness, so the sequence matters on a multi-member cluster. The sections that follow assume you already run a multi-member etcd cluster and have confirmed that snapshot backups are working, because every recovery path on this page depends on having a known-good copy of the data.
Automatic compaction or scheduled compaction: which setup fits
etcd keeps a history of every revision of every key, and that history grows with every write the API server makes. Compaction discards old revisions so the database stops growing with history that no client needs anymore. Compaction does not reclaim disk space on its own. It marks space inside the database file as free, and defragmentation is the separate step that returns it to the filesystem. Kubernetes exposes two routes to compaction: the kube-apiserver can compact on a schedule it controls, or an operator can run compaction manually against etcd. Both routes end in the same etcd operation, so the choice is about who triggers it, how often, and how you observe it.
- Revision history: Every update to an object creates a new revision, so high churn objects such as leases, events and heavily reconciled custom resources drive growth.
- Compaction target: Compaction keeps the most recent revisions needed by watches and discards the rest, so it never removes current object state.
- Space reclaim: Freed pages stay inside the database file until defragmentation runs, which is why compaction alone rarely lowers the on-disk size.
- Scope: The operation is cluster wide, since all keys share one revision sequence.
- Observation: Watch the database size and the revision numbers so you can see whether compaction is keeping pace.
Before choosing a setup, confirm how your distribution already configures the API server's compaction flags, because many installers set them for you.",
Automatic compaction is configured on kube-apiserver through its etcd compaction settings. You can compact by time window or by revision count, and the API server then compacts on that schedule without any extra job. This suits most small and medium clusters with predictable churn, because it needs no separate tooling and keeps running after the operators who set it up have moved on. Its main limit is that it applies one policy to the whole cluster and gives you little control over timing, so a compaction cycle can fall in the middle of a busy period.
- Time based: A fixed window keeps history for a set duration, which is easy to reason about for audit and watch needs.
- Revision based: A fixed count of revisions keeps the history size more predictable when write rates vary.
- Low operational cost: No cron job, no extra service account and no extra failure point are needed.
- Limited timing control: You cannot easily run compaction in a quiet maintenance window with this option.
- Configuration path: Confirm whether the flag is set by kubeadm, your distribution's packaged defaults or a managed control plane, since changing it may require a restart of the API servers.
When you change the policy, check that compaction still runs fast enough to keep the database below your quota. Confirm the exact flag names and default values for your Kubernetes minor version in the official reference before editing manifests.",
Manual compaction is run as a scheduled job, often a CronJob or a systemd timer on a control plane node, that calls etcdctl to compact up to a revision captured at run time. This suits clusters with high or bursty write rates, strict change windows, or teams that need compaction logged and tied to a runbook. It gives you control over when the work happens and makes each run visible, at the cost of an extra component you must build, secure and monitor. A failed job silently lets history grow, so an alert on the job's last success is part of the design.
- Precise timing: Run compaction during low traffic, and pair it with a defragmentation window on each member.
- Explicit revision: The job reads the current revision and compacts up to it, which avoids compacting data a slow watch still needs if you add a safety margin.
- Extra access: The job needs etcd client certificates and must be restricted, because it holds write access to the datastore.
- Monitoring: Alert on job failures and on database size, not only on job success.
- Interaction with automatic settings: Running both policies at once can cause duplicate work, so disable one unless you have a documented reason to keep both.
Before you adopt a scheduled job, confirm with your distribution whether automatic compaction is already active and which etcd client version it ships, since command syntax and certificate paths differ between installers.
The right setup depends less on node count than on how many writes reach etcd and how quickly history accumulates. Large clusters with many controllers, operators, leases and events generate far more revisions than a small cluster with few workloads, even when both have the same number of control plane nodes. A cluster that churns through deployments, CI pipelines or custom resources will fill its quota faster than one with stable workloads. The question to answer is how fast your database grows between compaction cycles, and whether a single automatic policy keeps that growth below the space quota with margin.
- Small, stable clusters: Automatic periodic compaction usually keeps pace with little tuning.
- Large or busy clusters: Consider a scheduled job so you can compact more often and pair it with defragmentation in a planned window.
- Bursty workloads: Batch jobs, progressive delivery and frequent rollouts make revision-count policies harder to predict, so measure the database size during peaks.
- Lease and event churn: Controllers that update leases often can dominate revision growth, so reduce unnecessary writes where possible.
- Measurement: Record database size and revision growth over at least one normal and one peak period before choosing a policy.
Ask your distribution vendor or your platform team for the observed write rate and database growth on comparable clusters, and treat any figure you are given as an estimate that depends on your workloads.
Before choosing, establish what your installed distribution already does, because the default may already be correct or may conflict with a custom job. kubeadm clusters take their API server flags from a static pod manifest on each control plane node. Packaged distributions and managed control planes may set compaction flags in their own configuration and may not expose them to you at all. The Kubernetes operating etcd guide and the kube-apiserver reference describe the flags and the etcd operations, but the defaults you run are the ones your installer chose for your minor version. Confirm them on every control plane node, since drift between nodes is a common cause of confusing behavior.
- Flag inventory: Record the compaction settings on each kube-apiserver and whether any are overridden in installer configuration.
- Existing jobs: Search for CronJobs, timers or scripts that already call etcd compaction or defragmentation.
- Client tooling: Confirm the etcdctl version and the certificate paths available to any job you plan to run.
- Managed control planes: Ask the provider which compaction and defragmentation behavior they run, and what you can change.
- Change control: Treat compaction settings as control plane configuration, and test any change on a non-production cluster first.
Write down the chosen setup, its owner and the alert that proves it is working, so the decision survives staff changes.
Configuration options for compaction, defragmentation and quotas
This table compares the four settings that control how much space etcd uses and how it reports pressure: auto-compaction retention, the backend quota, defragmentation scheduling and alarm monitoring. Read each row as a lever with its own trade-off, and confirm the default and flag names for your etcd and Kubernetes versions before changing anything on a production control plane.
| Setting | What it controls | When it fits | Trade-off |
|---|---|---|---|
| Auto-compaction retention | How much revision history etcd keeps before older revisions are discarded from the keyspace | Clusters with heavy object churn, such as frequent Lease, Event or CI-driven updates, where old revisions accumulate | Shorter retention frees space sooner but narrows the window for watch clients that resume from an older revision |
| Backend database quota | The maximum size of the etcd backend database before etcd raises a space alarm and stops accepting most writes | Sizing headroom against the storage you have, within the limits your etcd version supports | A larger quota tolerates more growth but leaves more data to compact, defragment and snapshot, and a larger database can slow recovery |
| Compaction schedule (manual or automated) | When and how often compaction runs against the revision history, separate from the retention setting | Operators who want compaction timed to quiet periods or who must evidence each run in change records | Manual runs add operational work and can be forgotten; automated runs must be monitored so they do not fail silently |
| Defragmentation schedule | When etcd members rewrite the backend file to return free pages to the filesystem | After large compactions, since compaction marks space free without shrinking the file on disk | Defragmentation blocks the member while it runs, so run it one member at a time and confirm leader health between members |
| Space usage alarm (NOSPACE) | The alarm etcd raises when the quota is reached, after which writes are rejected except for a few maintenance operations | Every production cluster, as the signal that compaction and defragmentation did not keep up | The alarm is a hard stop for writes, so alerting must fire well before the quota is reached |
| Monitoring of database size and fragmentation | Backend size, in-use size and the gap between them, tracked per member | Clusters where the gap between allocated and in-use space grows over time | Metrics need dashboards and alert thresholds that your team owns; confirm metric names for your etcd version |
| Snapshot and backup timing | When etcd snapshots are taken relative to compaction and defragmentation | Any cluster where a snapshot must reflect a known, compacted state | Taking snapshots during heavy compaction or defragmentation adds load, so sequence them deliberately |
How the space quota alarm behaves and why writes stop
When etcd reaches its backend space quota, it raises a NOSPACE alarm and stops accepting writes, which halts every change the control plane tries to make. The cards below cover what the alarm does, why the impact extends beyond writes, how to catch it early, and which quota settings your environment must confirm.
The NOSPACE alarm trigger
etcd keeps a backend database with a configured space quota. When the database reaches that size, etcd raises a NOSPACE alarm and rejects further writes. Compaction and defragmentation both free space, but neither can help until you confirm which member raised the alarm and how close the others are to the limit. Check the alarm list on every member, not only the leader.
etcd operations docsWrites stop cluster-wide
Once the alarm is active, every write to the keyspace fails, including object creates, updates, deletes and lease renewals. Controllers, the scheduler and kubelet status updates all depend on those writes, so cluster activity freezes even though the API server still responds. Existing workloads keep running for a while, but nothing new gets scheduled or reconciled.
Why reads and the control plane still suffer
Reads can still succeed, but the API server and controllers retry failed writes, which adds load and log noise. Leases that cannot be renewed can cause nodes and leader election to flap. Confirm how your control plane behaves during a freeze by reviewing kube-apiserver and controller logs from a test cluster, since the exact symptoms vary with version and workload.
Detecting the alarm before it fires
Track the database size per member over time and alert well before the quota is reached, using the etcd metrics exposed by each member. Trend the growth rate against your compaction schedule, so a rising line gives you time to act. Alerting only on the NOSPACE alarm means you are already in an outage when it fires.
Quota size and limits to confirm
Confirm the configured backend quota on every member, the default in your etcd version, and whether your distribution overrides it. Ask your team or vendor for the largest expected object count and churn rate, then check that the quota leaves headroom for a full defragmentation cycle. Record these values in the runbook, since changing the quota requires a member restart.
Recovering from NOSPACE without losing the control plane
This sequence clears an etcd space quota alarm while keeping every member healthy and the Kubernetes control plane writable, with a snapshot in hand before any data is removed.
Confirm the NOSPACE alarm and database size
Run
etcdctl alarm listagainst each member and check the endpoint status output for database size and raft index. The operator confirms which members report NOSPACE and whether the alarm is cluster-wide, since etcd raises it once a member reaches its configured quota. Done when every member's alarm state and database size are recorded, and you know whether the API server is returning write errors.Protect quorum before changing anything
Before any write-side action, confirm that every etcd member is reachable and that a majority is healthy, using
etcdctl endpoint healthwith the cluster certificates. Stop any automation or GitOps sync that writes heavily to the cluster for the duration of the recovery, so the compaction target does not move underneath you. Done when all members answer and no member is already in a failed or syncing state. If quorum is at risk, stop here and follow the separate runbook for lost members.Take a snapshot before changing data
Save a snapshot from a healthy member with
etcdctl snapshot save, store it outside the etcd data directory, and check it with the snapshot status tooling your version provides. The snapshot is the rollback point if compaction or a later step removes something you need. Done when the snapshot file exists on a separate disk or host, its hash or status is recorded, and a second copy is stored in a location the cluster does not depend on.Compact history to the current revision
Read the current revision from the endpoint status, then run
etcdctl compactionto that revision on the cluster. Compaction discards old revisions but leaves the live keyspace intact, and it frees space inside the database file without shrinking it on disk. Done when the command returns successfully and the revision you compacted to matches the one you read. Allow the members to settle before continuing.Defragment members one at a time
Run
etcdctl defragagainst a single member, wait for it to finish and confirm its health, then move to the next. Defragmentation blocks that member while it rewrites the database, so doing one member at a time keeps the remaining members serving reads and writes. Done when each member reports healthy after its defrag and the database size on disk has dropped. Do not defragment all members in parallel.Disarm the space alarm
Once the database size is below the quota with headroom, run
etcdctl alarm disarm. Etcd keeps the cluster in read-only mode while the alarm is set, so disarming is what returns write access to the API server. Done whenetcdctl alarm listreturns no entries and a test write through a non-critical key succeeds.Verify member health and write latency
Check
etcdctl endpoint healthandendpoint statuson every member, confirm a single leader and matching raft indexes, and measure write latency against the baseline you recorded earlier. Confirm the kube-apiserver has resumed normal writes and that controllers are reconciling without errors. Done when all members are healthy, indexes converge, latency is back near the baseline, and you have noted the cause of growth so the quota and compaction settings can be reviewed.
Scheduling defragmentation without disrupting the API server
Defragmentation should be scheduled one etcd member at a time, never all at once. Defragmentation rewrites the backend database file to give back disk space that compaction has freed inside it. While a member runs it, that member cannot serve reads and writes normally, so the kube-apiserver requests routed to it slow down or stall. In a three-member cluster, a defragmentation that runs on every member simultaneously can take away quorum entirely. The safe pattern is to defragment a follower first, confirm it is healthy and in sync, move to the next follower, and leave the leader for last. Confirm the current leader with etcdctl endpoint status before you start, because the leader can change during the window and your runbook must handle that.
Choose the window using your own traffic data, not a generic recommendation. Look for the period when the API server sees the fewest writes, such as controller reconciliation and CI pipelines running at low volume, and avoid periods of cluster upgrades, certificate rotation or node drains. Ask whether your team can watch the cluster for the full duration, because a defragmentation on a large database can take longer than expected. Measure the effect on your own cluster in a non-production environment first: record request latency on the API server, etcd_disk_backend_commit_duration_seconds and leader election events before, during and after one member's run. Use those measurements to set the pacing between members and to decide whether the job can run unattended.
Coordinate the job with monitoring and change control. Silence or annotate the alerts that will fire while a member is busy, but keep alerts on leader changes, failed proposals and quorum loss active so a real fault is not hidden. Check that the cluster has no active alarms and that every member reports the same revision before starting. Write the procedure as a runbook that stops if a member fails its health check, and keep a fresh snapshot from etcdctl snapshot save on hand before any maintenance begins. Confirm the exact flags and metric names against the Kubernetes etcd operations documentation and the etcd release you run, since behavior can differ between versions.
Security and operational risks in etcd maintenance
Compaction, defragmentation and quota recovery all act on the same data store that holds cluster state and Secrets. The cards below cover the security exposure of etcd data and the operator mistakes that most often turn routine maintenance into a control plane outage.
Snapshots contain Secrets
An etcd snapshot is a full copy of cluster state, and Secrets are stored unencrypted in etcd by default unless encryption at rest is configured. Anyone who can read a snapshot can read every Secret in the cluster, including the copies taken before maintenance. Check where snapshots are written, who can read that location, how long copies are kept, and whether they are encrypted before they leave the node.
Secrets good practicesUnauthorized client endpoint access
The etcd client port accepts requests from anything that can reach it, and a client with write access can alter cluster state directly, bypassing the API server's admission and RBAC checks. Restrict the client port to control plane members and the tooling that needs it, require client certificate authentication, and confirm that maintenance jobs run with the same restricted credentials rather than a shared administrator key.
Compaction that removes needed history
Compaction discards old revisions of keys, so a compact revision set too high can remove history that a lagging watcher or a restore procedure still expects. Before compacting, confirm the revision you intend to keep, check that no component is far behind, and take a fresh snapshot so a bad compaction has a recovery point. Record the revision used so the step can be audited later.
Defragmenting several members at once
Defragmentation blocks reads and writes on the member being defragmented while it rewrites its database. Running it on all members at the same time can remove quorum for the duration, which turns a maintenance window into an outage. Work through members one at a time, confirm each is healthy and caught up before starting the next, and keep the leader for last so leadership moves during the run are controlled.
Quota recovery run by hand
When a member hits the space quota, the cluster stops accepting writes until the alarm is cleared, and recovery under pressure invites shortcuts such as deleting keys or raising the quota without a plan. Document the exact commands for compaction, defragmentation and alarm disarm, rehearse them in a non-production cluster, and agree who has the authority to run them. Confirm the procedure with your Kubernetes version's etcd documentation before the incident.
Monitoring gaps on database size
Without alerting on database size and active alarms, growth goes unnoticed until writes fail, and by then the fastest fix is an emergency change. Watch the database size per member, the number of revisions retained, the alarm state and the time since the last successful snapshot. Set thresholds with your team after measuring a normal baseline, and route alerts to someone who runs maintenance on call.
Questions teams ask before bringing in outside help with etcd
What drives the cost of etcd compaction and defragmentation work?
The main driver is how many clusters and etcd members are in scope and how much change the team needs to make in the live control plane. Cost comes from planning the maintenance window, reviewing current compaction settings, checking disk and database size trends, running defragmentation member by member, and writing the runbook and alert thresholds your team keeps afterward. Clusters with many nodes, many objects created and deleted often, or no existing monitoring usually take longer to assess. Ask any provider for a quote that lists each cluster, the number of etcd members, whether the work includes a NOSPACE recovery option, and which artifacts (runbook, alert rules, dashboards) you keep at the end.
How long does an etcd maintenance engagement take, and what sets the duration?
Duration depends on the number of clusters, how much assessment is needed, the size of the database and the change windows your organization allows. Defragmentation is done one member at a time, and each member must be healthy before the next one starts, so cluster size and disk speed affect how long the work runs. Approval cycles for production changes often take longer than the technical steps. Ask for a written schedule that separates assessment, a test run in a non-production cluster, the production change window and the handover, and confirm which of those steps your change board must approve.
What does the work need from our team before it starts?
The work needs access to the control plane nodes or a bastion host with the right certificates, read access to etcd metrics, and a named contact who can approve changes during the window. You should provide a recent etcd snapshot taken with etcdctl snapshot save and confirmed restorable, Prometheus or equivalent metrics covering etcd_mvcc_db_total_size_in_bytes and disk usage, a change window that includes a rollback path, and written confirmation of which namespaces and workloads are business critical. Ask your provider to list every access path and credential they need, and to confirm how those are removed at the end.
Can our in-house platform team do etcd maintenance without outside help?
Yes, if the team has Linux administration experience, understands etcd quorum and the Kubernetes control plane, and can practice the steps outside production first. The core tasks are checking the endpoint status, reviewing the compaction revision, running defragmentation on one member at a time, and clearing the space alarm after a fix. The harder part is the decision in an incident: if a cluster is near its quota or already read-only, a wrong step can cost quorum. Teams that do this in-house usually document the runbook, rehearse it in a lab and keep a restore path tested. Outside help is most useful for the first assessment, for recovering from an active NOSPACE event, or for setting up monitoring that the team has not built before.
What happens if our cluster is already in NOSPACE?
When the etcd space quota is exceeded, etcd raises a NOSPACE alarm and rejects writes, which stops changes across the Kubernetes API even though reads may still work. Recovery usually means confirming the alarm, compacting old revisions up to a safe point, defragmenting members to release freed space, and then disarming the alarm. The priority is protecting quorum, so an experienced operator checks member health and takes a snapshot before any change. Ask any provider how they would verify each member before defragmentation, what they do if a member fails during the work, and how they confirm the control plane accepts writes again. If quorum is already lost, the work moves to the recovery runbook for control plane loss, which is a separate and riskier process.
Does the engagement cover security and compliance evidence for etcd?
etcd holds Kubernetes object data, including Secrets, which Kubernetes stores unencrypted in etcd by default unless encryption at rest is configured. Maintenance work touches that data path, so the change record, access logs and snapshot handling should be documented. Ask whether the scope includes reviewing encryption at rest, restricting who can reach etcd client ports and how snapshot files are stored and protected. Evidence for an audit comes from your own records and an independent assessor, so the engagement can prepare the controls and logs but does not produce an audit opinion.
What should we check when comparing providers for etcd maintenance?
Check whether the written scope names the etcd version, the cluster topology (stacked or external etcd), the monitoring and alerting to be set up, the rollback plan and the handover material. Ask how the provider handles production changes, who is on call during the window and what the retest or follow-up looks like after the first maintenance cycle. A useful quote separates one-time work from recurring work, such as scheduled defragmentation or ongoing support. DeployOpen plans and delivers engagements from a written scope, and its quotes follow from that scope, so compare providers on the same written list of clusters, tasks and deliverables.
Decision path from an etcd alarm to a healthy cluster
The path starts when writes slow down or an alarm fires on the control plane. Operators first confirm the NOSPACE alarm and the database size, then take a snapshot before changing anything. After that they run compaction, defragment one member at a time, disarm the alarm and verify health. If quorum is lost at any point, the branch leaves this procedure and moves to the separate recovery runbook, where etcd is restored from snapshot.
Steps to clear an etcd space alarm, with the quorum-loss exit to the recovery runbook.
How DeployOpen scopes and supports etcd maintenance
DeployOpen plans and implements self-hosted Kubernetes work inside the infrastructure you control, including the etcd maintenance setup described on this page. For compaction, defragmentation and space quota work, the scope usually covers reviewing the current --quota-backend-bytes setting, the compaction policy on the API server, the defragmentation schedule and alarm handling, and the runbook your operators will follow when an alarm fires. The starting point is an inventory of what you run today: the etcd version, the topology (stacked or external), the disks under each member and how the cluster behaves under write load. Confirm with your platform team which member count and disk class are already in place before scoping, because those decisions change how much maintenance work is needed.
Most engagements are fixed-scope. Scope, deliverables, timelines and the responsibilities of each party are agreed in writing before work starts, so you know what is changed on your clusters, what is handed over and what remains with your team. A quote follows from that written scope rather than from a published price list. Ask any provider for the items that drive the quote: the number of clusters and etcd members in scope, whether a staging cluster is available for rehearsing defragmentation and NOSPACE recovery, whether the work includes alert wiring into your monitoring stack, and whether the runbook must be tested on your hardware. Ongoing support, upgrades and periodic health checks can be covered by a retainer, which is priced separately from the initial work.
Work is documented for your operations team, not kept with the consultants. Deliverables typically include the configuration as it was set, the changes made, the maintenance schedule, the alarm and recovery procedures, and the verification steps used to confirm each change. Your engineers should be able to run a defragmentation window, clear an alarm and check member health without outside help. Before the engagement, confirm who on your side owns the runbook, how it is stored and reviewed, and how changes to etcd settings are approved, since those answers determine whether the documentation will still be accurate after the first Kubernetes upgrade.

