How does ECR registry storage cost actually accumulate?
ECR bills storage per GB-month for the compressed layer data a repository holds. The size shown for each image is not what you pay for. Images in a repository share layers, and each shared layer is stored once. What drives cost is the set of unique layers still referenced by at least one image.
This has two practical consequences:
| Action | Reported size | Storage actually freed |
|---|---|---|
| Delete one image whose base layers are shared with others | Full image size | Only layers no other image references, often a small app layer |
| Delete the last image referencing a large layer | Full image size | That layer plus any other orphaned layers, which can exceed what earlier deletions freed |
CI pipelines that push an image on every commit create untagged or short-lived tags. Each push adds a new layer delta, usually dependencies or build output, that nothing ever deletes.
Illustrative estimate (assumed numbers, not a benchmark)
- Formula: monthly growth (GB) = pushes per day × unique delta per push (GB) × repositories × 30
- Assume 20 pushes/day, a 0.15 GB delta, and 40 repositories: 20 × 0.15 × 40 × 30 = 3,600 GB added per month.
- Multiply by your region's per-GB-month storage price. Without cleanup, storage cost keeps growing month over month.
Check the bill before you build cleanup tooling. Spend may come mostly from data transfer, such as cross-region pulls or pulls from outside AWS. It may also come from a few large repositories, where targeted fixes beat a fleet-wide policy. Cleanup pays off for platform teams that own dozens or hundreds of repositories with high-frequency CI pushes, because growth there is steady and spread across the fleet.
What is an ECR lifecycle policy and how does it work?
An ECR lifecycle policy is a JSON document attached to a single repository. There is no registry-wide policy, so each repository carries its own copy. The policy holds a list of rules, and each rule has three parts:
rulePriority: a unique integer. Lower numbers are evaluated first.selection: defines which images the rule considers.tagStatusistagged,untaggedorany.- Tagged rules also take a
tagPrefixList(for examplerelease-) or atagPatternList(wildcards such asprod-*). countTypeis eitherimageCountMoreThan, which keeps the newest N, orsinceImagePushed, which takes acountUnitofdays.countNumbersupplies N or the day count.
action: always{"type": "expire"}.
A minimal policy might keep the last 20 images tagged release- at priority 1 and expire untagged images older than 7 days at priority 2. The example that follows annotates each field.
How does lifecycle policy evaluation work?
Once a policy is attached, ECR evaluates it for you in the background. You do not run a job, schedule anything or provide compute. ECR walks the rules in priority order, decides for each image which rule (if any) selects it, and marks images that meet a rule's expiry criteria. Expiration then happens asynchronously, some time after an image meets the criteria, not at the instant you save the policy. When an image expires, ECR deletes its manifest and tags, and any layers no remaining image references stop counting toward storage.
Several evaluation rules cause most of the surprises:
- Priority order. Rules run in ascending
rulePriority. - One rule per image. Once a rule selects an image, no lower-priority rule can expire it, even if the selecting rule kept it. A "keep the last 20
release-" rule therefore protects those images from a later age-based sweep. That protection is often what you want. anygoes last. AtagStatus: anyrule must have the highestrulePrioritynumber, so it runs after everything else.- Every tag counts. An image with several tags is matched against all of them. If an image is tagged both
release-42andsha-abc123, a broadsha-rule at a higher priority claims it first. The image is then counted and possibly expired under thesha-rule, and therelease-rule meant to protect it never applies.
Expiring removes the image digest and every tag on it.
{
"rules": [
{
"rulePriority": 1,
"description": "Rollback window: keep the newest 20 images with a tag starting with release-, expire older ones",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": ["release-"],
"countType": "imageCountMoreThan",
"countNumber": 20
},
"action": {
"type": "expire"
}
},
{
"rulePriority": 2,
"description": "Cleanup: expire untagged images (superseded pushes, orphaned layers) 7 days after push",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 7
},
"action": {
"type": "expire"
}
}
]
}
A minimal two-rule lifecycle policy. JSON has no comment syntax, so each rule's optional description field explains its intent: priority 1 keeps the newest 20 release- images, and priority 2 expires untagged images 7 days after push.
When should you use an ECR lifecycle policy?
Use a lifecycle policy when the images you want to delete can be identified by tag status, tag prefix or pattern, push age, or count. That covers most CI-driven repositories. Typical good fits:
- CI pushes on every commit or pull request. Untagged leftovers and
pr-or branch builds pile up steadily, and nobody needs them after a short window. - Many repositories owned by one team. A standard policy applied through infrastructure code bounds growth everywhere without per-repository attention.
- A consistent tagging convention. If releases, mainline builds and throwaway builds carry distinct prefixes, the policy can treat each class differently.
- Untagged churn from mutable tags. Re-pushing
latestor an environment tag leaves the previous digest untagged. A short untagged-expiry rule is the lowest-risk cleanup available. - You want cleanup without owning code. The policy is declarative, runs inside ECR, and needs no delete permissions held by your own tooling.
When should you avoid relying on an ECR lifecycle policy?
A lifecycle policy is the wrong tool, or not enough on its own, in these situations:
- Storage is not the cost problem. If the bill is dominated by data transfer or a handful of very large images, a retention policy will barely move it. Fix pull patterns or image size first.
- Tags do not encode intent. If release builds and throwaway builds share the same tag shapes, any rule broad enough to clean up will also hit releases. Fix the tagging convention before writing rules.
- Deletion must depend on what is deployed. The policy cannot see running ECS tasks, Kubernetes pods, Lambda functions or digests pinned in manifests. If a deployed image could fall outside your protected tags, you need an inventory-aware job (covered below) or a protected-prefix convention.
- Rarely built services. An age-based rule on a service that ships a few times a year can delete its only good image. Use count-based rules or exclude such repositories.
- Retention requirements. If audit or compliance rules require keeping every released artifact for a fixed period, make sure no rule selects those images, or keep the policy off those repositories entirely.
- Untagged artifacts you depend on. If your build or signing tooling stores indexes, signatures or attestations as untagged entries, an untagged-expiry rule can break pulls or verification. Confirm how they are stored first.
- The registry is small. If storage cost is negligible, the risk of a misconfigured rule may outweigh the savings. A single untagged-image rule is usually as far as you need to go.
What should an ECR lifecycle policy never delete?
A lifecycle policy evaluates only what ECR stores: tags, push dates and image counts. It has no knowledge of which images running ECS tasks, Kubernetes pods or Lambda functions use, or which digests are pinned in Helm values and manifests. An image that is serving production traffic looks the same to the policy as an abandoned build.
Deleting a referenced image usually does not break anything right away, because running containers already have their layers. The failure appears later, whenever something needs to pull the image again. A scale-out event starts tasks that cannot start. A replaced node cannot reschedule its pods, which fail with image pull errors. A rollback to last week's release fails at the moment you need it most. Lambda functions backed by container images can also fail when the image they reference is gone.
Aggressive retention lowers storage cost, but it also shortens your rollback window. During an incident, the release you need may be exactly the one that was expired. A few dozen extra images usually cost far less than one extended outage.
Mutable tags such as latest or env-prod make this harder, because they move between images. The digest that production actually runs may no longer carry any tag. Enabling tag immutability and deploying by digest makes references stable and easier to protect. It also requires changes to CI and deployment tooling.
Practical mitigations:
- Set generous counts for any rule that touches releasable images.
- Use a distinct tag prefix for images that have been deployed, and keep it out of expiry rules.
- Before deletion, run an inventory step that collects digests in use across clusters, services and functions, and compare it with the expiry candidates.
How do you design a layered retention policy around your tagging convention?
Lifecycle rules can only select images by tag status, tag prefix or tag pattern, and push age or count. They cannot see deployment state, branch names or commit metadata. Your tagging convention is the only way intent reaches the policy. If main-, pr- and release tags share no consistent structure, you cannot write a rule that targets one without hitting the others.
A layered policy for a typical service looks like this:
- Untagged images: expire them after one or two days. These are mostly leftovers from re-pushed mutable tags.
main-images: keep the last N. This preserves a rollback window that does not depend on how recently you shipped.pr-andfeature-images: expire them by age, such as 14 days after push.- Semver release tags: match them in no rule at all. ECR has no explicit "keep" action, so protection means exclusion. Do not add a catch-all
anyrule, because it would sweep releases in.
| Rule type | Strength | Failure mode |
|---|---|---|
Count (imageCountMoreThan) |
Predictable footprint in active repositories | A burst of builds can push out the image currently deployed |
Age (sinceImagePushed) |
Bounds staleness regardless of build volume | Can delete the only good image of a rarely built service |
Untagged does not always mean garbage. Multi-architecture indexes, per-platform manifests, signatures and attestations can appear as separate or untagged entries. Deleting them can break pulls or signature verification for an image whose tag still exists. Before you enable the untagged rule, check how your build and signing tooling stores these artifacts.
{
"rules": [
{
"rulePriority": 10,
"description": "Untagged leftovers from re-pushed mutable tags. Confirm indexes, signatures and attestations are not stored untagged first.",
"selection": { "tagStatus": "untagged", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 2 },
"action": { "type": "expire" }
},
{
"rulePriority": 20,
"description": "Rollback window: keep the newest 30 main- images however old they are",
"selection": { "tagStatus": "tagged", "tagPrefixList": ["main-"], "countType": "imageCountMoreThan", "countNumber": 30 },
"action": { "type": "expire" }
},
{
"rulePriority": 30,
"description": "PR builds are disposable after two weeks",
"selection": { "tagStatus": "tagged", "tagPrefixList": ["pr-"], "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 14 },
"action": { "type": "expire" }
},
{
"rulePriority": 40,
"description": "Feature builds use their own rule because multiple prefixes in one list must ALL match",
"selection": { "tagStatus": "tagged", "tagPrefixList": ["feature-"], "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 14 },
"action": { "type": "expire" }
}
]
}
A layered ECR lifecycle policy that quickly expires untagged images, keeps the last 30 main- images, and age-expires pr- and feature- images. Semver release tags such as v1.4.2 are protected because no rule selects them and the policy has no catch-all "any" rule.
How can you test an ECR lifecycle policy before it deletes anything?
Expiration is irreversible. ECR has no recycle bin for expired images, so a rule with a wrong tagPrefixList or a broad rule placed at a lower priority number than a narrow one can remove release images. Once that happens, your options are to rebuild from the tagged commit, which may not produce an identical digest, or to push again from a copy kept in another registry or account. A rollback that relies on a digest pinned in a deployment manifest will fail either way.
Run the preview first
aws ecr start-lifecycle-policy-preview evaluates a draft policy against a repository without deleting anything. aws ecr get-lifecycle-policy-preview then returns each image that would expire and the rule priority that matched it. Read that list for any tag you would roll back to. Also check the priority attached to each result. If a release tag shows up under your catch-all rule, the ordering is wrong. A preview with no results also needs a second look, because it often means a prefix doesn't match your real tags.
Applying a policy does not delete images immediately. ECR expires matching images asynchronously, some time after the policy takes effect. This means the preview is your real checkpoint. Watching the repository for a few minutes after applying the policy proves nothing.
Audit actual usage
aws ecr describe-images returns imagePushedAt for each image and, where ECR has recorded it, lastRecordedPullTime. Treat the pull time as approximate. An image that was pushed long ago but pulled recently is still in use, so it should be protected by an explicit rule. Count-based or age-based rules will not keep it safe.
#!/usr/bin/env bash
set -euo pipefail
REPO="payments-api" # placeholder repository name
POLICY="file://lifecycle-policy.json" # draft policy, not yet applied
aws ecr start-lifecycle-policy-preview \
--repository-name "$REPO" \
--lifecycle-policy-text "$POLICY"
aws ecr wait lifecycle-policy-preview-complete --repository-name "$REPO"
aws ecr get-lifecycle-policy-preview \
--repository-name "$REPO" \
--query 'previewResults[].{priority: appliedRulePriority, tags: imageTags, pushed: imagePushedAt, digest: imageDigest}' \
--output table
aws ecr describe-images \
--repository-name "$REPO" \
--query 'sort_by(imageDetails, &imagePushedAt)[].{tags: imageTags, pushed: imagePushedAt, lastPull: lastRecordedPullTime}' \
--output table
This script previews which images a draft ECR lifecycle policy would expire and which rule matched each one, then lists push and last-pull times so you can check actual usage before you apply the policy.
How do you roll out lifecycle policies across many repositories?
Doing this by hand in the console does not scale past a handful of repositories. Each repository ends up with a slightly different policy, nobody remembers why, and new repositories get created with no policy at all. Define the lifecycle policy in the same infrastructure code that creates the repository, whether that is a Terraform module, a CloudFormation template, or another tool you already use. A repository then cannot exist without a policy, and every change to retention goes through code review.
Standard default, explicit overrides
Write one default policy that encodes your tagging convention: protect release tags, keep a bounded number of branch builds, and expire untagged images quickly. Let a repository override specific values, such as a higher count for a service with a long rollback window. The override sits next to the repository definition, so a reviewer can see the exception and its justification. This removes the per-repository manual work. It also stops drift, because changing the default updates every repository that has not opted out.
Lifecycle policies are not copied by replication. If you replicate images to other regions or accounts, the destination repositories need their own policies, defined in the same code. Otherwise the replicas grow without limit while the source stays clean.
Measuring the result
- Storage: record each repository's summed image size from
aws ecr describe-imagesbefore the first cleanup and again after it. Layers can be shared between images, so treat this sum as a relative measure, not a billing figure. - Image counts: track tagged and untagged counts per repository over time. Counts should level off rather than keep rising.
- Untagged images after builds: check the untagged count a day after busy build periods. If it keeps rising, a rule is not matching what your pipeline produces.
#!/usr/bin/env bash
set -euo pipefail
REGION="${AWS_REGION:-us-east-1}" # repeat for each replication destination region
OUT="ecr-snapshot.csv"
TODAY="$(date -u +%Y-%m-%d)"
[ -f "$OUT" ] || echo "date,region,repository,tagged,untagged,summed_bytes" > "$OUT"
for repo in $(aws ecr describe-repositories --region "$REGION" \
--query 'repositories[].repositoryName' --output text); do
# The CLI paginates automatically, and --query runs over the combined results.
read -r tagged untagged bytes < <(aws ecr describe-images \
--region "$REGION" --repository-name "$repo" \
--query '[length(imageDetails[?imageTags]), length(imageDetails[?!imageTags]), sum(imageDetails[].imageSizeInBytes)]' \
--output text)
# Layers can be shared between images, so summed_bytes is a relative measure, not a billing figure.
echo "$TODAY,$REGION,$repo,$tagged,$untagged,$bytes" >> "$OUT"
# A repository whose untagged count stays high a day after builds probably lacks the untagged-expiry rule.
if [ "$untagged" -gt 20 ]; then
echo "WARN: $repo in $REGION has $untagged untagged images" >&2
fi
done
A script that appends a dated row per repository with tagged and untagged image counts and summed image size, so you can compare storage before and after cleanup and confirm untagged counts stay low across source and replica regions.
How can lifecycle policies save engineering time?
Lifecycle policies save time mainly by removing recurring manual work and the custom tooling teams otherwise write to replace it:
- No cleanup scripts to own. ECR runs the evaluation and deletion. You do not maintain a scheduled job, its compute, its credentials, or the
ecr:BatchDeleteImagepermission that job would need. - No periodic cleanup tickets. Without a policy, someone eventually notices registry cost, investigates which images are safe to delete, and deletes them by hand. A policy turns that into a one-time design decision.
- New repositories are covered automatically. When the policy lives in the module that creates repositories, nobody has to remember to configure retention.
- Retention changes are a code review, not a project. Changing the default count or window is a one-line change that applies everywhere that has not overridden it.
- Faster investigations. When retention is uniform and documented in code, answering "why is this image gone?" means reading the policy and checking the preview, not reconstructing who ran which script.
Illustrative estimate (assumed numbers, not a measurement)
- Formula: hours saved per year = manual cleanup sessions per year × hours per session − one-time setup hours − yearly review hours
- Assume 4 manual cleanup sessions a year, each taking 6 engineer-hours to inventory, verify and delete; 8 hours of one-time setup to write the default policy, wire it into infrastructure code and run previews; and 4 hours a year of review.
- With those assumptions: 4 × 6 − 8 − 4 = 12 engineer-hours saved in the first year, and 4 × 6 − 4 = 20 hours in later years. Substitute your own session count and duration; the saving scales with the number of repositories each manual session has to cover.
The time saving only holds if the policy is correct. A rule that expires a release image costs far more engineering time in incident response than it ever saved, which is why the preview step and the protected-tag convention are part of the setup cost, not optional extras.
What are the alternatives when a lifecycle policy is not enough?
A lifecycle policy only evaluates image age, count, and tag patterns within a single repository. It cannot ask "is this digest running in production right now?" It also cannot ask "has anything pulled this in 90 days?" beyond what its rule criteria support, or "does another repository still reference this base image?" Rules like these need a custom cleanup job.
A workable job lists images per repository, including the lastRecordedPullTime field that DescribeImages returns. It then collects every image digest referenced by running workloads in your clusters and subtracts both from the deletion candidates. Build it with three safeguards:
- Dry-run as the default. The job should log candidates and require an explicit flag to delete.
- Structured logs for every deletion, recording repository, digest, tags, and the reason.
- A hard allowlist of repositories and tag patterns the job must never touch.
The cost is real. You own the code, and the job needs ecr:BatchDeleteImage, a permission that turns a bug into data loss. A job that stops running or cannot reach a cluster fails silently, so alert on missed runs and on zero-candidate results. You also give up a managed, declarative mechanism that AWS runs for you.
| Approach | Development cost | Risk | Maintenance |
|---|---|---|---|
| Do nothing | None | Cost growth only | None |
| Lifecycle policy only | Low | Low if protected tags are excluded | Low |
| Policy + custom job | Medium | Medium | Medium |
| Custom job only | High | Highest | High |
Lean toward doing less when the registry is small. A few hundred gigabytes of images may cost less per month than an hour of debugging a deletion that broke a rollback. In that case, a minimal untagged-image rule is enough.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to ecr lifecycle policy, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.