DEV Community

Cover image for Your CloudWatch Log History Dies With the Log Group. Here's How to Keep It.
Polliog for AWS Community Builders

Posted on

Your CloudWatch Log History Dies With the Log Group. Here's How to Keep It.

In July I wrote The CloudWatch to S3 Tables Mirror Is Not an Archive. The short version:

  • CloudWatch Logs can mirror your log groups into S3 Tables (Apache Iceberg), queryable from Athena, at no extra storage cost.
  • The mirror follows the log group's retention. Set 30 days and you have 30 days of Iceberg data.
  • Delete the log group and the mirror goes with it. The AWS docs say it plainly: "When you delete a log group or log stream, CloudWatch Logs also removes the data from the S3 table bucket."

That post ended on the problem. This one is about the fix: how to keep a copy of your logs that survives both retention and deletion, without paying CloudWatch prices for it.

There are four reasonable answers. I'll go through each with the commands, the place where it breaks, and a monthly cost for the same workload. The cost model is a script you can rerun with your own numbers.

Four ways to keep CloudWatch log history: (0) longer retention plus deletion protection, still inside CloudWatch; (1) export tasks to an S3 bucket; (2) a subscription filter into Firehose writing an Iceberg table; (3) a scheduled Athena job copying the mirror into your own S3 table. Only 1, 2 and 3 survive deleting the log group

Two ways to lose logs

Before picking a tool, be precise about what you're protecting against, because the options don't cover the same failures.

  1. Retention. Every event older than the log group's retention is deleted, in CloudWatch and in the mirror. This is not an accident, it's the setting doing its job. The risk is that the setting is short (because CloudWatch storage is the expensive kind) or that someone shortens it.
  2. Deletion. Someone, or more often some tool, deletes the log group. A cdk destroy, a Terraform refactor that renames a resource, a cleanup script with a loose prefix match. The log group goes, and the mirror goes with it.

A real archive has to survive both. Keep that in mind for option 0.

Option 0: keep it in CloudWatch, and lock the door

Since November 2025 CloudWatch Logs has deletion protection for log groups:

aws logs put-log-group-deletion-protection \
  --log-group-identifier "/app/api" \
  --deletion-protection-enabled
Enter fullscreen mode Exit fullscreen mode

With it on, DeleteLogGroup fails with a ValidationException until someone turns protection off (--no-deletion-protection-enabled). It's free, it's one command, and you should probably enable it on every log group you care about regardless of what else you do.

Combine it with a longer retention and you get something surprisingly decent. The mirror follows retention, so a 12-month retention also means 12 months of Iceberg data you can query from Athena. CloudWatch bills storage on the compressed size, at $0.03 per GB-month in us-east-1. At 100 GB/month of raw logs and an 8:1 compression ratio, a full year of history is about 150 GB stored, or $4.50 a month.

Where it breaks:

  • It doesn't touch retention. Events still expire on schedule, and anyone with logs:PutRetentionPolicy can shorten the window. If you go this way, deny that action outside your platform role (an SCP works well for this).
  • It's still one switch. Protection can be turned off by anyone with the permission to do so, and then the next destroy works. That's better than nothing, but it's a speed bump, not a copy.
  • Same account, same service. If your requirement says "logs must survive a compromised account" or "logs must be immutable for N years", nothing inside CloudWatch meets it.

If none of those three matter to you, stop here. Seriously. Turn on protection, raise retention, query the mirror. The rest of this post is for when you need a copy that lives somewhere else.

Option 1: export tasks to S3

The oldest tool. CreateExportTask copies a time range of one log group into an S3 bucket:

aws logs create-export-task \
  --log-group-name "/app/api" \
  --from "$(date -u -d '2 days ago 00:00' +%s)000" \
  --to   "$(date -u -d 'yesterday 00:00' +%s)000" \
  --destination "my-log-archive" \
  --destination-prefix "api/$(date -u -d '2 days ago' +%F)"
Enter fullscreen mode Exit fullscreen mode

--from and --to are milliseconds since the epoch. The bucket needs a policy that lets logs.amazonaws.com write to it, and it must be in the same Region as the log group. It can be in another account, which matters if you want the archive out of reach of the account that produces the logs.

What you get is a set of gzip-compressed text files. That's both the strength and the weakness: the objects are plain S3 objects, so everything S3 offers works on them. Lifecycle rules to Glacier Flexible Retrieval ($0.0036 per GB-month), Object Lock for immutability (supported for export destinations), replication to another Region. And nothing about them depends on CloudWatch anymore.

Where it breaks:

  • One export at a time. Each account can have one active export task per Region, and it's not a quota you can raise. With 40 log groups you're writing a loop that starts a task, waits for it to finish, and starts the next.
  • It lags. Log data "can take up to 12 hours to become available for export", and tasks time out after 24 hours. That's why the example above exports the day before yesterday, not yesterday.
  • AWS doesn't recommend it for this. The docs literally say: "We recommend that you don't regularly export to Amazon S3 as a way to continuously archive your logs," and point to subscriptions instead.
  • It's text, not a table. Athena can read it, but you'll want a CTAS into Parquet before running real queries on it.

So why include it? Because it's the only option here that reaches backwards. The mirror only processes events that arrive after you associate the log group (the docs say existing data is not backfilled). A subscription filter only sees new events too. If you have 18 months of history in CloudWatch today and want it out before you shorten retention, export tasks are how you get it. Use them once, for the backfill, and something else going forward.

Option 2: subscription filter → Firehose → Iceberg

This is the option AWS points you to, and it's the most "proper" pipeline: every event is pushed out as it arrives, into a table you own.

The pieces:

  1. A table bucket in S3 Tables with the AWS analytics integration enabled, a namespace, and a table with an explicit schema.
  2. A Firehose stream, source Direct PUT, destination Apache Iceberg Tables, with CloudWatch Logs decompression and message extraction turned on. Without them, Firehose receives gzip blobs in the CloudWatch envelope instead of your log lines. Message extraction is free; decompression is $0.00325 per GB.
  3. A subscription filter on each log group:
aws logs put-subscription-filter \
  --log-group-name "/app/api" \
  --filter-name "to-archive" \
  --filter-pattern "" \
  --destination-arn "arn:aws:firehose:us-east-1:123456789012:deliverystream/logs-archive" \
  --role-arn "arn:aws:iam::123456789012:role/cwl-to-firehose"
Enter fullscreen mode Exit fullscreen mode

An empty filter pattern sends everything. The Iceberg table now grows continuously, it has nothing to do with the log group's lifecycle, and you can set CloudWatch retention as short as your on-call needs.

Where it breaks:

  • Your logs must be JSON. The Iceberg destination expects one JSON object per record, and top-level field names and types have to match the table's columns. Plain-text logs need a Lambda transform in the stream, which is one more thing to own.
  • Standard log class only. Subscription filters don't work on Infrequent Access log groups. If you moved log groups to IA to save on ingestion, this option is off the table for them.
  • Five filters per log group. Usually fine, but if your log groups already feed an observability vendor and a SIEM, you're closer to the limit than you think. There's also one account-level subscription filter per Region, which is the easier way to cover everything.
  • At-least-once delivery. Duplicates are possible. For an archive that's usually acceptable; for counting things, dedupe in the query.
  • Throughput. Direct PUT into the Iceberg destination is limited to 5 MiB/s per stream in us-east-1, us-west-2 and eu-west-1, and 1 MiB/s in other Regions. That's 400+ GB a day, plenty for most, but it's a number to check rather than discover.
  • Only new events. Same as the mirror: it starts when you create the filter.

On cost, Firehose is the most expensive line in this post. Writing to Iceberg tables via Direct PUT is $0.075 per GB in us-east-1. I couldn't find a clear statement on whether that GB is the gzip payload CloudWatch sends or the decompressed data, so the model below shows both ends: $5.71 to $12.27 a month at 100 GB/month, including S3 Tables storage and compaction.

Option 3: the mirror plus a copy job

This is the one I'd actually use if I were already on the mirror.

The mirror already does the hard part. It turns your logs into an Iceberg table, partitioned by day on cwl__timestamp, and it does it for free. The only problem is that it forgets. So copy what it has into a table bucket you own, on a schedule, before retention takes it away.

Athena can read from one S3 table bucket and write to another in the same statement: CTAS on S3 Tables arrived in August 2025, and AWS's own walkthrough includes copying from one table bucket to another. I'll use the S3 server access log table from the July post as the example.

Once: seed the archive with everything the mirror currently holds. On S3 Tables you leave out location and table_type (Athena defaults to Iceberg there), and the data is written as Parquet by default.

CREATE TABLE "s3tablescatalog/log-archive"."logs"."s3_server_access"
WITH (partitioning = ARRAY['day(cwl__timestamp)'])
AS SELECT *
FROM "s3tablescatalog/aws-cloudwatch"."logs"."amazon_s3__server_access"
WHERE cwl__timestamp <= current_timestamp - INTERVAL '2' HOUR;
Enter fullscreen mode Exit fullscreen mode

Every day: copy what's new.

INSERT INTO "s3tablescatalog/log-archive"."logs"."s3_server_access"
SELECT *
FROM "s3tablescatalog/aws-cloudwatch"."logs"."amazon_s3__server_access"
WHERE cwl__timestamp > COALESCE(
        (SELECT max(cwl__timestamp)
         FROM "s3tablescatalog/log-archive"."logs"."s3_server_access"
         WHERE cwl__timestamp > current_timestamp - INTERVAL '30' DAY),
        current_timestamp - INTERVAL '30' DAY)
  AND cwl__timestamp <= current_timestamp - INTERVAL '2' HOUR;
Enter fullscreen mode Exit fullscreen mode

Three details in that query do all the work:

  • The watermark is the archive itself. No state table, no Step Functions. The job copies everything newer than the newest row it already has, so running it twice doesn't duplicate anything.
  • It filters on cwl__timestamp, not on the event's own time. This is the rule from the July post: late-delivered records get a later cwl__timestamp, so a window on that column never skips them. A window on the event time would.
  • The two-hour margin. The mirror isn't instant. As long as its lag is under two hours, stopping two hours short of now means every row in the window has already landed, so the next run can safely start from the max. Check your own lag by comparing max(cwl__timestamp) in the mirror with the current time, and adjust.

The 30 must match the log group's retention. It bounds the subquery so it doesn't scan the whole archive, and if the job has been broken for longer than retention, the COALESCE falls back to "copy everything the mirror still has". At that point the gap is already gone from CloudWatch anyway.

Timeline of the copy job: the mirror holds the last 30 days; the archive already has everything up to its newest cwl__timestamp; each run copies from that point to two hours before now, and the next run starts where this one stopped

Schedule it with EventBridge Scheduler, which can call Athena directly through a universal target. No Lambda needed:

aws scheduler create-schedule \
  --name copy-s3-access-logs \
  --schedule-expression "cron(15 3 * * ? *)" \
  --flexible-time-window Mode=OFF \
  --target '{
    "Arn": "arn:aws:scheduler:::aws-sdk:athena:startQueryExecution",
    "RoleArn": "arn:aws:iam::123456789012:role/scheduler-athena",
    "Input": "{\"QueryString\": \"<the INSERT above>\", \"WorkGroup\": \"archive\"}"
  }'
Enter fullscreen mode Exit fullscreen mode

Where it breaks:

  • Failures are silent. If the query fails, nothing tells you. Add an EventBridge rule on Athena's Athena Query State Change events with state FAILED for that workgroup and send it somewhere a human reads.
  • SELECT * is a bet on the schema. If the mirror's table gains a column, the INSERT stops matching the archive. List the columns explicitly if you want the job to survive that, and add new ones on purpose.
  • Workgroup encryption. Athena can't run writes (INSERT, UPDATE, DELETE, MERGE) on S3 Tables from a workgroup that uses SSE-KMS or CSE-KMS for query results. Use a dedicated workgroup for the job.
  • Permissions live in Lake Formation. Reading the aws-cloudwatch tables needs the same Lake Formation grants you set up to query the mirror, and the job's role also needs to write to the archive namespace.
  • Only what the mirror has. Like option 2, it starts from the moment you associated the log group. For older history, option 1 once.

I haven't been able to find a cleaner way to get a durable Iceberg copy of CloudWatch logs. You get the schema AWS already maintains, no Firehose, no JSON requirement, and the cost is a daily Athena query. In the model below I priced the worst case, where every run scans the full 30-day window of both tables, and it still comes to about $8 a month.

Retention on the archive: not a lifecycle rule

For option 1, an S3 lifecycle rule is the right tool: expire or transition objects after N days.

For options 2 and 3, don't. An Iceberg table is metadata pointing at specific data files. Expire files by age from under it and queries start failing on missing objects. Retention on an Iceberg table is a SQL statement:

DELETE FROM "s3tablescatalog/log-archive"."logs"."s3_server_access"
WHERE cwl__timestamp < current_timestamp - INTERVAL '400' DAY;
Enter fullscreen mode Exit fullscreen mode

S3 Tables' own maintenance (snapshot expiration and unreferenced file removal) then removes the files. If old data is rarely read, S3 Tables also has an Intelligent-Tiering storage class; in us-east-1 its colder tiers are priced at $0.0144 and $0.0046 per GB-month, against $0.0265 for standard S3 Tables storage.

What it costs

Same workload for every option: 100 GB/month of raw logs into CloudWatch (Standard class), 12 months of history kept, 8:1 compression for anything stored. Options 1 to 3 keep 30 days in CloudWatch. Prices are us-east-1, first tier, from the AWS Price List API as of late November 2026.

Monthly cost to keep 12 months of history at 100 GB/month: option 0 $4.50, option 1 $1.16 to $3.82, option 2 $5.71 to $12.27, option 3 $8.09, compared with $50 a month of CloudWatch ingestion that every option pays

Option $/month Survives deletion Backfills history Format
0. Retention + deletion protection 4.50 only while protection is on n/a CloudWatch + mirror
1. Export tasks to S3 1.16 – 3.82 yes yes gzip text
2. Subscription → Firehose → Iceberg 5.71 – 12.27 yes no Iceberg (your schema)
3. Mirror + Athena copy job 8.09 yes no Iceberg (AWS schema)

The low end of option 1 moves everything older than 30 days to Glacier Flexible Retrieval; the high end keeps it all in S3 Standard.

The honest takeaway is in the chart, not the table: at this volume, the archive is a rounding error next to ingestion. You're paying $50 a month to get the logs into CloudWatch, and $1 to $12 to keep them. Ten times the volume is ten times every line. Pick on failure modes, not on price.

Which one

  • You only fear accidents, and a year is enough: option 0. Protection on, retention up, an SCP on PutRetentionPolicy. Query the mirror.
  • You have history in CloudWatch you want to keep: option 1, once, for the backfill. Then one of the others.
  • You're already using the mirror: option 3. It's the least new infrastructure for a real copy.
  • Your logs are JSON, you want your own schema, or you're not on the mirror: option 2.
  • Compliance wants immutable or cross-account: option 1 (or Firehose writing to a plain bucket) into a bucket in a separate account with Object Lock. Iceberg tables are for querying; a locked bucket of files is for auditors.

Combinations are normal. Mine would be deletion protection everywhere, a one-off export for the history, and the copy job for everything after.

When the mirror is enough

Not every log group needs an archive. If the logs are only useful for debugging the last few weeks, if nothing legal depends on them, and if the log group is under deletion protection, the mirror is exactly what you want: free, queryable, gone when it stops mattering. "It expires with the log group" is only a problem when nobody decided that it should.

The script

costs.py: the cost model behind the chart and the table
#!/usr/bin/env python3
"""Monthly cost of keeping CloudWatch log history, four ways.

Steady state: 12 months of history already accumulated, 100 GB/month of raw
logs ingested into CloudWatch Logs (Standard class). Prices: us-east-1, from the
AWS Price List API (offers/v1.0, AmazonCloudWatch / AmazonKinesisFirehose /
AmazonS3 / AmazonAthena, publication dates 2026-11-20..25). First pricing tier
only, free tier ignored. Change the inputs and rerun.
"""
RAW_GB_PER_MONTH = 100    # raw log volume ingested per month
MONTHS_KEPT      = 12     # history you want to keep
COMPRESSION      = 8      # raw : stored (gzip / Parquet). Assumption, measure yours.
CW_RETENTION_M   = 1      # CloudWatch retention when something else is the archive
RUNS_PER_MONTH   = 30     # copy-job runs per month (option 3)

P = dict(
    cw_ingest        = 0.50,     # $/GB, custom logs, Standard class
    cw_store         = 0.03,     # $/GB-month, CloudWatch log storage (billed compressed)
    s3_standard      = 0.023,    # $/GB-month, first 50 TB
    s3_glacier_flex  = 0.0036,   # $/GB-month, Glacier Flexible Retrieval
    s3t_store        = 0.0265,   # $/GB-month, S3 Tables, first 50 TB
    s3t_compact_gb   = 0.005,    # $/GB processed by compaction (binpack)
    s3t_compact_obj  = 0.002e-3, # $/object compacted
    s3t_monitor_obj  = 0.025e-3, # $/object/month monitored
    fh_iceberg       = 0.075,    # $/GB, Firehose PutRecord -> Apache Iceberg Tables, tier 1
    fh_decompress    = 0.00325,  # $/GB decompressed (CloudWatch Logs records)
    athena_tb        = 5.00,     # $/TB scanned
)

raw    = RAW_GB_PER_MONTH
stored = raw / COMPRESSION                 # GB/month once compressed
hist   = stored * MONTHS_KEPT              # GB of compressed history at steady state
cw_short = stored * CW_RETENTION_M * P["cw_store"]   # the 30-day copy left in CloudWatch

def s3t_upkeep(gb_hist, gb_new, files_new):
    objs = gb_hist * 1024 / 256            # assume ~256 MB files after compaction
    return (gb_hist * P["s3t_store"] + objs * P["s3t_monitor_obj"]
            + gb_new * P["s3t_compact_gb"] + files_new * P["s3t_compact_obj"])

opts = {}
# 0. Keep it in CloudWatch: 12-month retention + deletion protection. Mirror stays free.
opts["0  CloudWatch, 12-month retention"] = (hist * P["cw_store"], hist * P["cw_store"])
# 1. Daily export task to S3 (gzip text). No CloudWatch line item for export tasks.
s3_std = cw_short + hist * P["s3_standard"]
s3_gla = cw_short + stored * P["s3_standard"] + (hist - stored) * P["s3_glacier_flex"]
opts["1  Export task -> S3 (Standard / Glacier after 30d)"] = (s3_gla, s3_std)
# 2. Subscription filter -> Firehose -> S3 Tables. Firehose may bill the gzip payload
#    (low) or the decompressed bytes (high): both shown.
files = 30 * 24 * 12                       # one file per 5-minute buffer flush
fh_lo = stored * P["fh_iceberg"] + raw * P["fh_decompress"]
fh_hi = raw * P["fh_iceberg"] + raw * P["fh_decompress"]
up = s3t_upkeep(hist, stored, files)
opts["2  Subscription -> Firehose -> S3 Tables"] = (cw_short + fh_lo + up, cw_short + fh_hi + up)
# 3. Mirror (free) + scheduled Athena copy into your own S3 table.
#    Worst case: every run scans everything the mirror still holds (the whole
#    CloudWatch retention window) plus the same window of the archive.
scan_gb = RUNS_PER_MONTH * 2 * stored * CW_RETENTION_M
cp = cw_short + scan_gb / 1024 * P["athena_tb"] + s3t_upkeep(hist, stored, RUNS_PER_MONTH)
opts["3  Mirror + Athena copy job -> S3 Tables"] = (cp, cp)

print(f"{raw} GB/month raw, {MONTHS_KEPT} months kept, {COMPRESSION}:1 compression "
      f"-> {hist:.0f} GB of history")
print(f"CloudWatch ingestion (same for every option): ${raw * P['cw_ingest']:.2f}/month\n")
print(f"{'option':52s} {'$/month':>14s}")
for k, (lo, hi) in opts.items():
    v = f"{lo:.2f}" if abs(hi - lo) < 0.005 else f"{lo:.2f} - {hi:.2f}"
    print(f"{k:52s} {v:>14s}")
Enter fullscreen mode Exit fullscreen mode

The defaults are guesses about your logs, especially the compression ratio. Change them and rerun; it prints the same table.

Which one are you running today, and has a log group ever disappeared on you? I'd like to hear how it happened.

Top comments (1)

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

The watermark-from-the-archive in option 3 is a nice touch, no state table to lose. On the "has a log group disappeared" question, the classic way I know of is a Terraform resource rename or module refactor without a moved block: the plan shows destroy plus create for aws_cloudwatch_log_group and the history goes with the old one. lifecycle { prevent_destroy = true } on log groups, plus a CI step that fails when any aws_cloudwatch_log_group appears in the plan's destroy list, catches it before apply. Deletion protection is a good second lock, but the plan check fails earlier and for free. The same applies to log groups Lambda creates on its own: they sit outside the stack, so they survive the function but keep infinite retention unless you manage them.