etcd compaction, defragmentation and space quotas

Long-running Kubernetes clusters can fill their etcd database and stop accepting writes. This page explains how compaction, defragmentation and the space quota alarm work together, and how to recover from NOSPACE without losing the control plane.

On this page

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.",

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.

SettingWhat it controlsWhen it fitsTrade-off
Auto-compaction retentionHow much revision history etcd keeps before older revisions are discarded from the keyspaceClusters with heavy object churn, such as frequent Lease, Event or CI-driven updates, where old revisions accumulateShorter retention frees space sooner but narrows the window for watch clients that resume from an older revision
Backend database quotaThe maximum size of the etcd backend database before etcd raises a space alarm and stops accepting most writesSizing headroom against the storage you have, within the limits your etcd version supportsA 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 settingOperators who want compaction timed to quiet periods or who must evidence each run in change recordsManual runs add operational work and can be forgotten; automated runs must be monitored so they do not fail silently
Defragmentation scheduleWhen etcd members rewrite the backend file to return free pages to the filesystemAfter large compactions, since compaction marks space free without shrinking the file on diskDefragmentation 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 operationsEvery production cluster, as the signal that compaction and defragmentation did not keep upThe alarm is a hard stop for writes, so alerting must fire well before the quota is reached
Monitoring of database size and fragmentationBackend size, in-use size and the gap between them, tracked per memberClusters where the gap between allocated and in-use space grows over timeMetrics need dashboards and alert thresholds that your team owns; confirm metric names for your etcd version
Snapshot and backup timingWhen etcd snapshots are taken relative to compaction and defragmentationAny cluster where a snapshot must reflect a known, compacted stateTaking 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 docs

Writes 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.

  1. Confirm the NOSPACE alarm and database size

    Run etcdctl alarm list against 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.

  2. 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 health with 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.

  3. 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.

  4. Compact history to the current revision

    Read the current revision from the endpoint status, then run etcdctl compaction to 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.

  5. Defragment members one at a time

    Run etcdctl defrag against 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.

  6. 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 when etcdctl alarm list returns no entries and a test write through a non-critical key succeeds.

  7. Verify member health and write latency

    Check etcdctl endpoint health and endpoint status on 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 practices

Unauthorized 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.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.