Everyone thinks a storage lifecycle manager is a nightly cron that runs a query. “List the objects older than 30 days, call the move API on each one, done - it is a for loop over a database.” That mental model survives exactly until you put real numbers on it: you have ten billion objects, not ten thousand. The “database” of object metadata is itself sharded across hundreds of machines, so there is no single table to SELECT from. The move is not free - it physically rewrites or re-references petabytes and some of those moves take hours (restoring from archive is not instant). And the whole time your scanner is grinding through metadata, customers are reading and writing those same objects at millions of requests per second, and a tier transition that pauses a live GET for even a few milliseconds is a customer-visible outage. The naive loop blocks the read path, double-moves objects when it retries, loses its place when it crashes, and would take weeks to finish one pass over the namespace.

A lifecycle manager is deceptive because the toy version (move old files to cheaper storage) looks trivial and the real version is a distributed systems problem in disguise. The hard part is not “decide this object should move” - that is a policy check. The hard part is doing it at the scale of billions of objects, without ever blocking the live read and write paths, and correctly under partial failure so that every object eventually lands in exactly the right tier, each object moves once not twice, and a scanner crash mid-pass does not lose progress or corrupt an object’s location. The whole design comes down to a few non-obvious decisions: a distributed metadata scanner that partitions the namespace into shards and processes them independently so no single machine is the bottleneck; idempotent tier-transition tasks keyed so a retry is a no-op instead of a second move; a reconciliation loop that treats partial failures as the normal case and drives every object to its correct tier eventually; and a hard rule that the lifecycle path and the live data path are decoupled so a transition never stalls a customer request.

Let me do it properly.

Functional Requirements (FR)

In scope:

  • Define lifecycle policies per bucket/prefix. A policy is a set of rules: “objects under logs/ move to cold after 30 days, to archive after 90, expire after 365,” or “transition to warm after 60 days of no access.” Rules key off age, prefix, tags, size, and access recency.
  • Evaluate policies against every object continuously. The system scans the object namespace, evaluates each object against the applicable policy, and decides the target tier for it right now.
  • Transition objects across tiers. Move an object between hot (SSD, lowest latency, highest cost), warm (cheaper, slightly higher latency), cold (cheap, seconds to first byte), and archive (cheapest, minutes to hours to restore). Transitions can be forward (hot to cold) or, on restore, backward.
  • Access-pattern-driven tiering (intelligent tiering). Beyond static age rules, track per-object access recency and auto-transition objects that have gone cold (not accessed in N days) down a tier, and promote frequently accessed objects back up.
  • Expiration / deletion. A policy can expire objects (hard delete, or delete old versions / incomplete multipart uploads) after a deadline.
  • Restore from archive. A GET on an archived object, or an explicit restore request, triggers a rehydration that moves it to a readable tier within the tier’s restore SLA.
  • Idempotent, resumable transitions. A transition that is retried, or a scan that resumes after a crash, must not double-move or corrupt an object. Every object eventually converges to its correct tier.
  • Visibility and reporting. Report how many objects are in each tier, projected vs realized cost savings, transition throughput, and lag (how far behind the scanner is).

Explicitly out of scope (say it so you own the scope):

  • The object storage data plane itself. We assume an existing object store (S3/GCS-style) that durably stores bytes, exposes a metadata service, and offers a mechanism to physically place an object on a given storage class. We manage lifecycle - deciding and orchestrating transitions - not the block storage, erasure coding, or placement internals.
  • The live read/write API. Customers PUT/GET/DELETE through the existing object store API. We do not sit in that path. We only annotate metadata and drive background transitions; the data path reads our tier pointer but is not served by us.
  • Billing and the pricing model. We emit the events and tier-residency data billing consumes, but computing invoices is a separate system.
  • Cross-region replication and DR. Lifecycle runs per region against that region’s namespace; replication of objects across regions is a different subsystem. We note where they interact but do not build it.
  • Strong real-time transitions. A newly-eligible object does not transition the same millisecond. Lifecycle is a background, eventually-consistent process with a bounded lag target, not a synchronous one.

The one decision that drives everything: a lifecycle manager at scale is not a query-and-loop - it is a distributed scanner that partitions the object namespace into independent shards, a stateless pool of transition workers that execute idempotent, keyed tier-moves pulled from a queue, and a reconciliation loop that treats every move as something that might half-finish and drives the namespace toward correctness continuously. The scanner never touches the live data path; it reads metadata and emits transition tasks. That separation - partitioned scan, idempotent keyed transitions, continuous reconciliation, and a strict wall between lifecycle and the live request path - is what buys scale, correctness under partial failure, and zero impact on customer reads and writes, and everything below is a consequence of it.

Non-Functional Requirements (NFR)

  • Scale: on the order of 10 billion objects in a region, growing; total stored data in the hundreds of petabytes; object metadata is a few KB each. Policies number in the thousands (one or more per bucket). The scanner must complete a full pass over the namespace within a bounded window (target: a full evaluation pass per day) so that an object becomes eligible and transitions within roughly a day of crossing a policy threshold.
  • Live-path impact: zero measurable impact on customer GET/PUT/DELETE latency or availability. The lifecycle system must not add latency to the hot path, must not lock objects a customer is reading, and must throttle its own metadata and data I/O so it never starves live traffic. This is the hardest constraint and the one that shapes the whole design.
  • Transition throughput: sustain hundreds of thousands of transitions/sec aggregate (a day’s worth of newly-eligible objects across 10B is large), with the physical move rate bounded by the data plane and by how much background I/O the system is allowed to consume.
  • Correctness: every object eventually lands in exactly the correct tier, moved exactly once per decision. No double-transitions (an object charged for two moves, or left in a half-moved state), no lost objects (an object whose metadata says tier X but whose bytes are not there), and no object stuck forever in a transitioning state. This is “effectively-once transition” built on an at-least-once task pipeline.
  • Durability: a transition must never lose data. The invariant is that an object’s bytes exist in at least one readable tier at all times during a move; the metadata pointer flips to the new tier only after the new copy is durable, and the old copy is reclaimed only after the pointer flip is committed.
  • Availability: 99.95%+ on the control plane (policy management, restore requests, reporting). The scanner and transition pipeline are background and tolerate pauses - being down for an hour means transitions lag an hour, not that anything breaks - but they must resume without losing progress.
  • Consistency: the tier pointer in object metadata is strongly consistent (a GET must always read the object from where it actually is, never a stale location). Policy evaluation and scan progress are eventually consistent - it is fine for the scanner to be slightly behind.

Back-of-the-Envelope Estimation (BoE)

Let me ground the design in numbers.

Namespace and scan load:

Objects in region:        10,000,000,000 (10B)
Full-pass target:         evaluate every object once per day
Scan rate required:       10B / 86,400s = ~116,000 objects/sec, sustained, all day
  -> this is a METADATA read rate. A single scanner cannot do 116K/s over 10B
     rows and finish in a day while staying off the live path. Must partition.
Metadata per object:      ~2 KB (key, size, tier, timestamps, tags, access stats)
Metadata footprint:       10B * 2 KB = ~20 TB of metadata (sharded across the
                          metadata service; the scanner reads it shard by shard).

The first non-obvious number: the scan is a metadata problem, not a data problem. 116K metadata evaluations/sec sustained for a full day is the floor just to keep up with a daily pass; a single process reading a 20 TB sharded metadata store that fast, without disrupting the live metadata reads that serve customer GETs, is impossible. The scan must be partitioned across the same shard boundaries the metadata store already uses, and it must read from replicas, not the primaries the live path hits.

Transition (write) load:

Fraction eligible per day: assume ~1% of objects cross a policy threshold daily
Newly-eligible/day:        10B * 1% = 100,000,000 transitions/day
Transition rate:           100M / 86,400s = ~1,160 transitions/sec average
Burst (policy change):     a NEW policy applied to a 5B-object bucket makes
                           billions eligible AT ONCE -> cannot do them all now;
                           must be a bounded, throttled backfill over days.
Data moved (if avg object = 4 MB): 100M * 4 MB = ~400 TB/day of physical moves
                           = ~37 Gbps sustained of background transition I/O,
                           which MUST be throttled below the headroom the live
                           path leaves - transitions yield to customer traffic.

Restore load (archive rehydration):

Restores:                  a small fraction of archived GETs, say 10,000/sec peak
Restore latency:           archive tier SLA is minutes to hours; the system
                           tracks a restore job per object and flips tier when ready
Restore staging:           restored objects live in a temp readable tier for a
                           TTL (e.g. 24h) then fall back -> extra transient storage

Scan-state / bookkeeping storage:

Per-shard scan cursor:     tiny (last-scanned key + watermark) per shard * thousands
                           of shards = negligible.
Transition task record:    object_key, from_tier, to_tier, state, attempt,
                           idempotency_key ~ 300 B. In-flight tasks at any moment:
                           if avg task takes 2s and rate is 1,160/s steady ->
                           ~2,320 concurrent steady; backfills push this to
                           millions in flight -> the task store + queue, not the
                           object metadata, is the hot bookkeeping component.

The headline shape: the scan is a sustained, partition-parallel metadata read that must stay off the live path; the transition rate is modest on average but has enormous backfill spikes (a policy change makes billions eligible at once) that must be throttled, not instantaneous; and the scarce resource is background I/O headroom, not storage. Size the scanner to finish a daily pass in parallel across shards, read metadata from replicas, cap transition I/O below live-traffic headroom, and treat a new/changed policy as a bounded multi-day backfill rather than a now-operation.

High-Level Design (HLD)

The system splits into planes. A control plane accepts and stores lifecycle policies and restore requests and serves reporting. A distributed scanner tier partitions the object namespace into shards, and each scanner owns a set of shards, reads their metadata from replicas, evaluates each object against the applicable policy, and emits a transition task when an object’s current tier differs from its target tier. A durable task queue holds transition tasks and decouples “decided to move” from “moved.” A stateless transition worker fleet pulls tasks and executes the physical tier move idempotently against the object store’s data plane, flipping the metadata tier pointer only after the new copy is durable. A reconciliation loop sweeps for objects stuck in a transitioning state and drives them to completion. A coordination service (Raft-based) assigns shards to scanners and holds scan watermarks. Crucially, the live read/write path is a separate system that the lifecycle manager only writes metadata into - it is never in the request path.

  CUSTOMERS (live path - NOT served by lifecycle)        ┌──── COORDINATION (Raft quorum) ─────────────┐
   GET / PUT / DELETE                                     │  - shard -> scanner assignment + leases     │
        │                                                 │  - scan watermarks / cursors per shard      │
        ▼                                                 │  - node liveness, failover reassignment     │
 ┌───────────────┐    reads tier pointer                  └──────────────┬───────────────────────────────┘
 │ OBJECT STORE  │    (strongly consistent)                             │ watch assignments
 │  DATA PLANE   │◄───────────────────────────┐                         │
 │  + METADATA   │                            │                         ▼
 │   SERVICE     │   metadata REPLICAS ────────┼──────►  ┌──────────────────────────────┐
 └──────┬────────┘   (scanner reads these,     │          │     SCANNER TIER (sharded)    │
        │             never the live primaries)│          │  scanner A owns shards {0,3}  │
        │                                       └──────────│  scanner B owns shards {1,4}  │
        │ 5. flip tier pointer (CAS)                       │  scanner C owns shards {2,5}  │
        │    AFTER new copy durable                        │  each: range-scan shard, eval │
        ▲                                                  │  policy, emit transition task │
        │                                                  └───────────────┬───────────────┘
        │ 4. write new copy to target tier, verify          2. evaluate     │ 3. emit task
        │                                                   policy per obj   ▼ (keyed, idempotent)
 ┌──────┴────────────────────────────────────┐          ┌──────────────────────────────┐
 │   TRANSITION WORKER FLEET (stateless)      │◄─────────│       TASK QUEUE (durable,    │
 │   pull task -> move -> flip pointer ->     │   pull   │       partitioned by shard)   │
 │   reclaim old copy -> ack                  │          └──────────────────────────────┘
 └──────┬─────────────────────────────────────┘
        │ 6. on partial failure / stuck state
        ▼
 ┌────────────────────────────────────────────┐          ┌──────────────────────────────┐
 │  RECONCILER (sweeps 'transitioning' rows,   │          │  POLICY STORE + REPORTING    │
 │  re-drives or rolls back to a clean tier)   │          │  (control plane)             │
 └─────────────────────────────────────────────┘          └──────────────────────────────┘

Request flow - defining a policy (control plane):

  1. An operator PUTs a lifecycle policy on a bucket/prefix (rules by age, prefix, tags, access recency, with target tiers and an expiration). The control plane validates it, versions it, and stores it. It does not immediately touch any object - it just makes the policy the one the scanner will evaluate against on its next pass. A new or changed policy that makes a huge population eligible is flagged as a backfill so the pipeline throttles it.

Request flow - scanning and deciding (the scan path):

  1. Each scanner owns a set of namespace shards (assigned by coordination). It range-scans its shards’ object metadata from a replica, and for each object loads the applicable policy and the object’s attributes (age, last-access timestamp, tags, current tier) and computes the object’s target tier right now.
  2. If the object’s current tier differs from its target tier, the scanner emits a transition task onto the durable queue, keyed by (object_id, target_tier, policy_version) so the task is idempotent. If current equals target, it does nothing. The scanner advances its per-shard watermark/cursor in coordination so a crash resumes mid-shard, not from the start.

Request flow - transitioning (the move path):

  1. A transition worker pulls a task. It first re-checks the object’s current state (the object may have been deleted, overwritten, or already moved since the scan - the task is a hint, not a command). If still eligible, it writes a new copy to the target tier in the data plane and verifies the copy is durable (checksum, replication/EC acknowledged).
  2. Only after the new copy is confirmed durable does it flip the object’s tier pointer in the metadata service with a conditional update (CAS on current tier + version). A live GET reads this pointer and is routed to wherever the bytes actually are, so the flip is the atomic cutover: before it, reads go to the old tier; after it, to the new; there is never a window with no readable copy.
  3. After the pointer flip commits, the worker reclaims the old copy (the bytes in the previous tier) and acks the task. If anything fails before the flip, the object still reads from the old tier (no harm); if the worker dies after the flip but before reclaiming, the reconciler notices an object in transitioning state with a committed new pointer and finishes the reclaim. Partial failure never leaves the object unreadable and never double-charges a move.

The key architectural insight: the scanner decides and emits hints, the worker verifies and executes, and the metadata tier-pointer flip - done only after the new copy is durable - is the single atomic cutover that keeps the live read path correct throughout. The scanner never mutates object data and never touches the live metadata primaries; it reads replicas and produces idempotent tasks. The worker owns the move but treats its input as stale and re-validates. The reconciler assumes every move can half-finish and makes “eventually correct” a background guarantee rather than something each worker must get perfectly right in one shot. That separation is what lets the system move billions of objects without ever blocking a customer request.

Component Deep Dive

Four hard parts: (1) the distributed metadata scanner - partitioning 10B objects so a full pass finishes in a day without a single bottleneck and without touching the live path; (2) idempotent, keyed tier transitions so a retry is a no-op and no object double-moves; (3) reconciling partial failures so every object converges to the correct tier with the bytes always readable; and (4) never blocking live reads and writes while moving petabytes in the background. I will walk each from naive to scalable.

1. The Distributed Metadata Scanner

We need to evaluate 10 billion objects against their policies every day. How we read the namespace is the whole ballgame.

Approach A: One scanner, one big query (the naive instinct)

A single process runs SELECT * FROM objects (conceptually), iterates, evaluates each, emits transitions.

scanner:
   for obj in objects:               # all 10B, one cursor
       target = evaluate(policy, obj)
       if obj.tier != target: emit_transition(obj, target)

Where it breaks: three ways at once. First, throughput: one process cannot read 116K objects/sec sustained for a day; a single pass would take weeks, so objects that crossed a threshold would transition weeks late. Second, the live path: the metadata store is sharded and serves customer GETs from its primaries; a full-table scan hammering those primaries steals IOPS from live reads and raises customer latency - the one thing we promised never to do. Third, resumption: one global cursor means a crash loses your place, or you restart the whole multi-week pass. A single scanner is a non-starter at this scale.

Approach B: Partition the namespace into shards, one scanner per shard-set

The metadata store is already sharded (say by a hash of the object key into thousands of partitions). Mirror that: split the namespace into K shards (far more than scanner nodes), assign each shard to exactly one scanner via the coordination service, and have each scanner range-scan only its shards.

shard = hash(object_key) % K        # same partitioning the metadata store uses
coordination: shard -> owner_scanner (+ lease), and a watermark per shard

scanner A owns {0, 3, 6, ...}: for each shard, range-scan FROM its watermark,
                               evaluate, emit, advance watermark periodically
scanner B owns {1, 4, 7, ...}: same, independently
adding a scanner -> some shards rebalance to it (scan throughput scales out)
losing a scanner -> its shards reassigned within a lease timeout, resume at watermark
  • Throughput scales with scanner count. 116K/sec spread across, say, 200 scanners is ~600 objects/sec each - trivial. Add scanners to finish faster or absorb growth. The partition boundaries match the metadata store’s own shards, so each scanner’s reads hit a bounded set of partitions.
  • Read from replicas, not primaries. The scanner reads object metadata from read replicas of the metadata store, so its sustained scan load never competes with the live GET/PUT traffic on the primaries. Slightly stale metadata is fine for a policy decision - if an object changed since the replica’s snapshot, the transition worker re-validates before moving (see part 2). This is the specific mechanism that keeps the scan off the live path.
  • Watermarks make it resumable and incremental. Each scanner periodically checkpoints a per-shard watermark (the last object key scanned, plus a pass timestamp) into coordination. A crash resumes from the watermark, not the start. Better, the scan can be incremental: order the shard scan by a column that changes when eligibility might change (last-modified, or a precomputed next_eligible_time), so most passes skip objects that cannot possibly have crossed a threshold yet.

Approach C: Event-driven + time-indexed, so you do not re-scan what cannot have changed

A pure periodic full scan re-reads 10B objects daily even though only ~1% become eligible. Cut that work two ways:

  • Precompute next_eligible_time per object. When an object is written or transitioned, compute the earliest wall-clock time it could next cross a policy threshold (e.g. “age > 30 days” from a 10-day-old object is 20 days away) and store it. Index objects by next_eligible_time. The scanner’s query becomes WHERE next_eligible_time <= now - a cheap range scan that touches only the small eligible slice, not the whole namespace. This turns a 10B-row daily scan into a ~100M-row daily scan.
  • React to live events for access-driven tiering. Access-pattern tiering (“not read in 30 days”) needs last-access data. Rather than the scanner polling, the live path emits access events (sampled, aggregated) to an access-stats store; a change in access recency updates the object’s next_eligible_time. The scanner still owns the decision and the move, but it is fed by events instead of brute-force polling. Policy-change backfills still require a full re-scan of the affected prefix, but that is a bounded, throttled special case, not the steady state.

The move that makes the scanner work: partition along the metadata store’s existing shard boundaries, read from replicas so you never touch live primaries, checkpoint a per-shard watermark for resumable incremental passes, and index objects by a precomputed next-eligible time so each pass evaluates the eligible slice, not the entire namespace. That is how a daily pass over 10B objects finishes in a day without a single bottleneck and without disturbing a single customer read.

2. Idempotent, Keyed Tier Transitions

The scanner emits a task saying “move object O to tier T.” A task can be delivered more than once (queue redelivery, scanner re-emits on the next pass before the first move finished, a worker retries after a lost ack). If each delivery moves the object, we get double-transitions: the object charged twice, or worse, moved to T, then an old in-flight task moves it again, corrupting its location.

Approach A: Treat the task as a command, execute it directly (naive)

Worker pulls “move O to T,” copies O to tier T, flips the pointer, deletes the old copy, acks.

Where it breaks: two deliveries of the same task both run. The first moves O to T and reclaims the hot copy. The second pulls, tries to copy “O from hot” - but hot is gone - or it copies the now-cold O to T again, flips a pointer that is already T, and reclaims a copy that is the only copy. In the bad interleaving you get a double move (billed twice) or data loss (the only readable copy reclaimed). The task-as-command model cannot survive at-least-once delivery.

Approach B: Idempotency key + re-validate + conditional flip

Make every transition idempotent and self-validating:

idempotency_key = hash(object_id, object_version, target_tier, policy_version)

worker on pull:
  1. LOAD current object metadata (authoritative, from primary): tier, version, state
  2. if object deleted/overwritten (version changed) -> DROP task (stale), ack
  3. if object.tier == target_tier -> already done, ack  (idempotent no-op)
  4. if a transition record for idempotency_key is 'committed' -> ack (dup)
  5. else: write new copy to target_tier, VERIFY durable
  6. CAS flip: UPDATE object SET tier=target, state=active, version=version+1
       WHERE object_id=O AND tier=current AND version=seen_version
     (fails if someone else moved/changed it -> re-evaluate or drop)
  7. record idempotency_key -> committed
  8. reclaim old copy, ack
  • The key makes retries no-ops. The idempotency key is deterministic from the object, its version, and the decision. A redelivered or re-emitted task computes the same key; step 4 sees it already committed and acks without moving anything. “It ran twice” becomes “it ran once and the duplicate was a no-op.”
  • Re-validation makes stale tasks safe. The scanner read a replica and may have been wrong-by-now (object deleted, overwritten, already moved). The worker loads authoritative metadata and drops the task if the premise no longer holds (steps 2-3). The task is a hint to re-evaluate, never a blind command. This is what lets the scanner safely read stale replicas.
  • The conditional flip (CAS) is the correctness linchpin. The pointer flip is conditioned on the object still being in the tier and version the worker saw. If two workers somehow both reach step 6 for the same object, only one CAS wins; the loser sees the precondition failed, drops its new copy (or lets GC reclaim it), and acks. There is no interleaving that produces two committed moves. Attach the version as a fencing mechanism so a delayed write from a slow worker that already lost the race is rejected.
  • Order of operations is the durability invariant. Copy-and-verify before flip, flip before reclaim. At every instant there is at least one readable copy: before the flip, the old tier; after the flip, the new tier. A crash between copy and flip wastes a copy (GC cleans it) but loses nothing. A crash between flip and reclaim leaves an orphan old copy (reconciler cleans it) but the object is already correct. Never reclaim before the flip is committed.

Idempotency keys turn redelivery into a no-op, authoritative re-validation turns stale scanner hints into safe decisions, and a version-fenced conditional flip ordered strictly after a durable copy guarantees exactly-once-effective transitions with the bytes always readable. Double-transitions become structurally impossible, not just unlikely.

3. Reconciling Partial Failures

A move has multiple steps across two systems (data plane copy, metadata flip, old-copy reclaim) and any step can fail or a worker can die between steps. We need every object to converge to a clean, correct state without a human in the loop.

Approach A: Hope the retry finishes it (naive)

Rely on the queue to redeliver a failed task; assume the retry completes the move.

Where it breaks: some failures are not retried because the worker died holding the task after partially mutating state, and nothing knows the object is half-moved. An object left in transitioning with a new copy written but pointer not flipped, or flipped but old copy not reclaimed, sits in limbo: the retry may never come (the task was acked, or lost), and no scan re-examines a transitioning object because it does not match a normal policy query. You accumulate orphaned copies (cost leak) and stuck objects (never reach the correct tier). Retry-only has no owner for the half-done state.

Approach B: Explicit transition state machine + a reconciler sweep

Give every object (or an associated transition record) an explicit state, and run a reconciler whose whole job is to find and fix objects not in a terminal state.

object/transition states:
  active(tier)            -- terminal, clean, bytes in `tier`
  copying(target)         -- new copy being written, not yet durable
  flipping(target)        -- new copy durable, pointer flip in progress
  reclaiming(old)         -- pointer flipped, old copy being reclaimed
  failed(reason)          -- gave up, needs attention

reconciler loop (continuous, partitioned like the scanner):
  scan for objects where state != active AND state_age > threshold:
    copying(T):     is the new copy durable?
                      yes -> advance to flipping   no (timed out) -> GC partial copy, reset to active(old)
    flipping(T):    did the CAS commit? (check metadata)
                      committed -> advance to reclaiming   not -> retry flip or roll back to active(old)
    reclaiming(O):  is the old copy gone?
                      yes -> set active(target)   no -> reclaim again (idempotent delete)
    failed:         alert, expose in reporting, allow manual or policy-driven retry
  • Every non-terminal state has an owner. A worker that dies mid-move leaves the object in copying/flipping/reclaiming. The reconciler, sweeping for state != active AND state_age > threshold, picks it up and drives it forward (or safely back). No half-move is orphaned, because “not active and old” is itself a query the reconciler runs continuously.
  • Roll forward or roll back, never stuck. From each intermediate state there is a deterministic resolution: if the new copy is durable, roll forward (finish the flip and reclaim); if it is not and has timed out, roll back (discard the partial copy, leave the object active on its old tier - it will simply be re-selected next scan). Because the flip is the atomic cutover, “roll back” before the flip is free (nothing customer-visible happened) and “roll forward” after the flip is just finishing the reclaim.
  • Reconciler is idempotent and uses the same CAS. Every reconciler action re-checks authoritative state and uses the same conditional updates workers use, so a worker and the reconciler acting on the same object at once cannot both win. Reclaims are idempotent deletes (deleting an already-gone copy is a no-op). The reconciler is not a special privileged path; it runs the same safe primitives, just triggered by “stuck” rather than “eligible.”
  • Orphan sweep for leaked copies. A separate background sweep lists physical copies in each tier and cross-checks them against the metadata pointer: a copy with no object pointing at it (a GC-missed partial copy or an un-reclaimed old copy) is a leak and is deleted after a grace period. This bounds the cost leak from crashes and makes storage self-healing.

The reconciler turns partial failure from an exception into the expected case: every object carries an explicit transition state, the reconciler continuously sweeps for anything not terminal-and-clean and deterministically rolls it forward or back using the same idempotent CAS primitives, and an orphan sweep reclaims leaked copies. Combined with the strict copy-before-flip-before-reclaim ordering, this is what delivers “every object eventually lands in exactly the right tier” under real-world failure.

4. Never Blocking Live Reads and Writes

The whole system moves petabytes in the background while customers read and write the same objects at millions of requests/sec. A transition must be invisible to them.

Approach A: Lock the object during the move (naive)

Take a lock on object O, copy it to the new tier, flip the pointer, release. Simple and obviously correct.

Where it breaks: a GET or PUT on O during the move blocks on the lock. Some moves (especially archive writes or large objects) take seconds to hours; a customer read stalling for seconds is an outage. And a PUT that overwrites O during the move either waits (bad latency) or invalidates the half-done copy (wasted work and a correctness headache). Locking the live object trades correctness-simplicity for the exact customer impact we are forbidden from causing.

Approach B: Lock-free via immutable copies and an atomic pointer flip

Never lock the live object. Exploit that a tier move is a copy to a new location plus a pointer swap, and object writes create new versions rather than mutating in place.

  • The move writes a new copy at a new location; reads keep hitting the old one. While the worker copies O to the target tier, the metadata pointer still points at the old tier, so every concurrent GET reads the old copy at full speed - the move is happening to a copy the live path is not looking at. No lock, no stall.
  • The flip is a single atomic metadata CAS - the only synchronization point. The cutover is one strongly-consistent conditional update of the tier pointer. Reads before it go to the old tier; reads after it go to the new tier; there is no in-between where a reader sees no copy. The CAS is a tiny, fast metadata write, not a data-plane operation, so it adds no meaningful latency even to a concurrent read of the same object.
  • Concurrent overwrite wins via versioning. If a PUT overwrites O mid-move, it creates a new object version with its own (hot) tier and a bumped version number. The worker’s flip is conditioned on the version it saw (step 6 in part 2); the overwrite bumped the version, so the CAS fails, the worker discards its now-stale copy, and the object stays correctly hot (the customer’s fresh write is authoritative). The overwrite never waited on the lifecycle move, and the lifecycle move correctly yields to the live write. The next scan re-evaluates the new version normally.
  • Restore (backward move) is the same pattern. A GET on an archived object cannot be served instantly (archive is minutes-to-hours). The read returns a restore in progress status (or blocks only if the client opted in), the system enqueues a restore task that rehydrates the bytes to a readable staging tier, and flips the pointer when ready - identical copy-then-flip mechanics, just toward a hotter tier, with a staging TTL after which the object falls back if not re-accessed.
  • Throttle background I/O below live headroom. Beyond locking, the move consumes metadata and data-plane I/O. Cap transition throughput with a rate limiter keyed on live-traffic headroom: measure live-path utilization and let background transitions use only the slack, backing off when customer traffic rises. This makes the lifecycle system a strict second-class citizen for I/O, which is exactly what “zero live-path impact” requires. Backfills (a new policy over billions of objects) run under the same throttle, spread over days.

Lock-free immutability plus an atomic pointer flip means the live path reads the old copy at full speed throughout the move and sees the new copy the instant the flip commits; version-conditioned flips make concurrent overwrites win cleanly without waiting; and a headroom-aware throttle keeps background I/O from ever starving customer traffic. The move is invisible to reads and writes because it never touches the object the live path is currently pointing at until the one-instant atomic flip.

API Design & Data Schema

Control-plane API (policies, restores, reporting)

PUT  /buckets/{bucket}/lifecycle                 # define / replace lifecycle policy
  { "rules": [
      { "id": "logs-tiering", "prefix": "logs/",
        "filter": { "tags": {"class":"log"}, "min_size_bytes": 0 },
        "transitions": [
          { "after_days": 30,  "to_tier": "cold" },
          { "after_days": 90,  "to_tier": "archive" } ],
        "access_tiering": { "demote_after_idle_days": 30, "promote_on_access": true },
        "expiration": { "after_days": 365 } } ] }
  -> 200 { "policy_version": 7, "estimated_affected_objects": 4200000000,
           "backfill": true }        # flags a throttled multi-day backfill

GET  /buckets/{bucket}/lifecycle                 -> current policy + version
POST /objects/{bucket}/{key}/restore             # rehydrate an archived object
  { "tier": "hot", "staging_ttl_hours": 24 }
  -> 202 { "restore_id": "...", "eta_seconds": 3600, "state": "in_progress" }
GET  /objects/{bucket}/{key}/lifecycle-status    -> current_tier, target_tier,
                                                    transition_state, next_eligible_time
GET  /buckets/{bucket}/lifecycle/report          -> objects+bytes per tier,
                                                    realized vs projected savings, scan lag

Internal API (scanner, worker, reconciler - mostly via the queue, not HTTP)

# scanner -> queue
EMIT_TRANSITION { object_id, bucket, key, from_tier, to_tier, object_version,
                  policy_version, idempotency_key }

# worker pulls from queue
PULL -> task (above) ; task invisible to others until lease_until
HEARTBEAT(task_id) -> extend lease while a long (archive) move runs
ACK(task_id)       -> move committed / no-op confirmed
NACK(task_id, err) -> requeue with backoff; dead-letter after max_attempts

# metadata flip (conditional, the atomic cutover)
CAS_TIER(object_id, expect_tier, expect_version, new_tier) -> ok | precondition_failed

Data model

The object metadata is the authoritative, strongly-consistent store that the live path also reads; it is sharded by object key and must support a point lookup (live GET), a conditional update (the flip), and a range scan by next_eligible_time (the scanner). Scan progress, tasks, and policies live in separate stores tuned to their access patterns.

objects (authoritative object metadata, sharded by hash(bucket,key)):

object_id          STRING   PRIMARY KEY     # bucket + key + version
bucket, key        STRING
version            BIGINT                   # bumped on every overwrite/transition; fencing
size_bytes         BIGINT
current_tier       ENUM     # hot | warm | cold | archive | staging
transition_state   ENUM     # active | copying | flipping | reclaiming | failed
target_tier        ENUM                     # null when active and correct
physical_locations JSON     # tier -> storage-backend handle(s); >1 only mid-move
last_modified      TIMESTAMP
last_access        TIMESTAMP                # fed by sampled access events
tags               JSON
policy_version     INT                      # policy this object was last evaluated under
next_eligible_time TIMESTAMP                # precomputed; drives the incremental scan
state_age          TIMESTAMP                # when transition_state last changed (reconciler)
created_at, updated_at TIMESTAMP

INDEX idx_eligible (shard, next_eligible_time)        # the incremental scan index (critical)
INDEX idx_stuck    (shard, transition_state, state_age)  # the reconciler sweep index
# point lookup on object_id is the live GET path

transition_tasks (in-flight move bookkeeping + idempotency ledger):

idempotency_key    STRING   PRIMARY KEY     # hash(object_id, version, to_tier, policy_version)
object_id          STRING   INDEX
from_tier, to_tier ENUM
state              ENUM     # queued | running | committed | dead_letter
attempt            INT
owner_worker       STRING
lease_until        TIMESTAMP
created_at, finished_at TIMESTAMP

UNIQUE (idempotency_key)     # a duplicate task collapses here -> no-op

Scan / coordination state (in the Raft quorum, tiny):

shard_assignment:  shard_id -> { owner_scanner, epoch (fence), lease_until }
scan_watermark:    shard_id -> { last_key_scanned, pass_started_at, pass_id }

policies (control plane) and access_stats (aggregated recency) are separate stores: policies are low-volume and read on every evaluation (cache them in scanners); access_stats is high-write, approximate, and only needs to be good enough to update next_eligible_time.

SQL vs NoSQL - the choice and why. The objects store wants strong consistency (the tier pointer must never be read stale by a live GET, and the flip is a conditional write), a secondary range index (next_eligible_time for the scan, transition_state for the reconciler), and horizontal sharding to tens of billions of rows. That points to a strongly-consistent distributed store with conditional writes and secondary indexes - a NewSQL system (Spanner/CockroachDB) or a horizontally-sharded store with per-key strong consistency (DynamoDB with conditional expressions and GSIs). The deciding factor is the version-fenced conditional flip: without a real compare-and-set on the authoritative row, you cannot prevent double-transitions, so an eventually-consistent store is wrong for objects. By contrast, transition_tasks is churny bookkeeping (a key-value/queue-backed store with a unique constraint is enough), access_stats is deliberately approximate (a sketch/aggregation store), and scan_watermark is tiny strongly-consistent coordination state (Raft/etcd). Match each store to its guarantee rather than forcing one database to do all four jobs.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each:

1. The scan becomes a full namespace sweep. Re-reading 10B objects every pass, or scanning the live metadata primaries, is the first thing to melt. Fix: the (shard, next_eligible_time) index so each pass evaluates only the eligible slice (~100M, not 10B), reads come from replicas not primaries, and the scan is partitioned per shard so throughput scales with scanner count. This index and the replica-read rule are the two most important performance decisions.

2. A single scanner is a throughput and availability bottleneck. One node cannot finish a daily pass and is a single point of failure. Fix: partitioned shard ownership (K shards » scanners, one owner each via coordination), per-shard watermarks for resumable incremental passes, and shard rebalancing on membership change. Scan throughput scales linearly with scanners.

3. Double-transitions from redelivered or re-emitted tasks. At-least-once delivery plus a scanner that re-emits before the first move finished. Fix: deterministic idempotency keys with a unique constraint (duplicate collapses to a no-op), worker re-validation against authoritative metadata, and a version-fenced conditional flip so only one move commits. Double-moves become structurally impossible.

4. Half-finished moves after a crash. A worker dies between copy, flip, and reclaim, leaving the object in limbo. Fix: an explicit transition state machine (copying/flipping/reclaiming) and a reconciler that sweeps transition_state != active AND state_age > threshold and deterministically rolls forward or back with the same idempotent CAS; plus an orphan sweep that reclaims leaked copies. Partial failure becomes the expected, self-healing case.

5. Live-path impact from background I/O. The move’s metadata and data I/O steals IOPS from customer reads/writes. Fix: read metadata from replicas, never lock the live object (immutable copy + atomic pointer flip), and throttle transition throughput to live-traffic headroom so background work uses only slack and backs off when customer load rises. Lifecycle is a strict second-class I/O citizen.

6. Policy-change backfill stampede. A new policy over a 5B-object bucket makes billions eligible at once. Fix: flag the policy change as a bounded, throttled backfill that spreads over days under the headroom rate limiter, rather than emitting billions of tasks now. Reporting exposes backfill progress and ETA. The steady-state pipeline is never asked to do a year of work in an hour.

7. Archive restore latency and staging cost. Rehydration takes minutes to hours and parks data in a readable staging tier. Fix: model restore as the same copy-then-flip task toward a hotter tier, return restore in progress on the live path (do not block), TTL the staging copy so restored objects fall back if not re-accessed, and track a restore job per object with an ETA. Staging storage is bounded by the TTL.

8. Hot shard in the scan or transition pipeline. One shard disproportionately eligible at once (a bucket whose objects all age past a threshold the same day). Fix: enough shards that any one is a small slice, hash by object key (not by a skew-prone attribute like bucket) so eligibility spreads, jitter next_eligible_time within a window so “all 30 days old today” does not fire in the same instant, and split a persistently hot shard and reassign it.

9. Task queue / bookkeeping overload during spikes. Backfills push millions of tasks in flight. Fix: partition the task queue by shard so pull throughput scales with workers, autoscale the stateless worker fleet on queue depth and oldest-task age (dispatch lag), and separate priority lanes (restores and expirations ahead of bulk cost-optimization backfills) so latency-sensitive work is not starved by a backfill.

10. Coordination service as a single point of failure. If shard assignment / watermarks die, scanners cannot fail over. Fix: run coordination as a replicated Raft quorum (3 or 5 nodes) with tiny state (assignments, epochs, watermarks); scanners cache their assignment so a brief coordinator blip does not stall in-flight scanning.

11. Metadata flip contention on a hot object. A frequently-overwritten object keeps failing the version-conditioned flip. Fix: that is correct behavior - a hot, frequently-written object should stay hot, so the flip losing to live writes is the system yielding as designed. Bound wasted work by not selecting objects written within a recency window (they are obviously still hot), so the scanner does not keep proposing moves that will lose.

12. Reclaim/GC lag and cost leak. Un-reclaimed old copies and GC-missed partial copies accumulate and quietly cost money. Fix: the orphan sweep cross-checks physical copies against metadata pointers and deletes unreferenced copies after a grace period, and reporting surfaces realized vs projected savings so a growing gap flags a reclaim backlog before it becomes a bill.

Wrap-Up

The trade-offs that define this design:

  • Scan decides, worker executes, flip is the only cutover. A partitioned scanner reads replicas and emits idempotent hints; a stateless worker fleet verifies against authoritative metadata and executes the move; the version-fenced pointer flip - done only after the new copy is durable - is the single atomic instant that moves the object for the live path. We trade a simple query-and-loop for independent scaling, replica reads that spare the live path, and a clean correctness story.
  • Idempotency and re-validation over trust. Every task is keyed so a retry is a no-op, and every worker treats the scanner’s hint as possibly stale and re-checks authoritative state before moving. This is what lets the scanner read cheap, slightly-stale replicas without ever causing a wrong or double transition.
  • Partial failure is the expected case, not an exception. An explicit transition state machine plus a reconciler that continuously sweeps for anything non-terminal, rolling forward or back with the same CAS primitives, plus an orphan sweep for leaked copies, is what delivers “every object eventually lands in exactly the right tier” under real crashes. Correctness is a background convergence property, not something each worker must nail in one shot.
  • The live path is sacred. Lock-free immutable copies, an atomic metadata flip, version-conditioned so concurrent overwrites win cleanly, and a throttle that caps background I/O to live-traffic headroom together guarantee a move is invisible to customer reads and writes. Lifecycle is a strict second-class I/O citizen by construction.
  • Backfills and restores are bounded special cases. A policy change over billions of objects is a throttled multi-day backfill, not a now-operation; an archive restore is the same copy-then-flip toward a hotter tier with a staging TTL. Neither is allowed to overwhelm the steady-state pipeline or the live path.

One-line summary: a distributed metadata scanner that partitions the object namespace into shards, reads replicas off the live path, and emits version-keyed idempotent transition tasks; a stateless worker fleet that re-validates and executes each tier move as copy-then-atomic-pointer-flip-then-reclaim; and a reconciler plus orphan sweep that drive every half-finished move to a clean, correct tier - so billions of objects migrate across hot, warm, cold, and archive continuously, exactly once each, without ever blocking a customer read or write.