Distributed Multi-Site Photo Deduplication System

Hard · System Design · Software Engineer · Technical Screen

Prompt

Evolve a single-machine duplicate-photo cleanup algorithm into a production distributed service operating over tens of millions of images stored across multiple hosts, cloud object buckets, and on-premises file servers for many independent customer tenants.

Design both the initial full-catalog sweep and ongoing day-two operations, grounding your choices in concrete throughput, memory, and infrastructure cost estimates while ensuring retries, concurrent runs, or stale metadata can never destroy a customer's last remaining copy of an image.

Scope & Expectations

  • Dedupe Index & Locality-Aware Batch Pipeline: Evaluate candidate stores (such as distributed key-value caches like Redis vs. durable databases) for the fingerprint index—covering key layout, RAM sizing, and eviction policies—and design a partitioned batch scanning and hashing pipeline (e.g., Spark) that keeps heavy reads local to storage.
  • Idempotency, Concurrency & Safe Deletion: Ensure exactly-once outcomes when retries or overlapping workers race on identical files, and incorporate live pre-delete verification, staged canary rollouts, reversible soft-delete/restore workflows, and immutable audit logs.
  • Incremental Operation & Fault Tolerance: Address continuous deduplication for newly uploaded photos, periodic background re-verification, crash recovery, storage backpressure, and operational telemetry (throughput, latency, failure rates).
  • Security & Tenant Isolation: Enforce least-privilege storage credentials and strict data separation across customer organizations.

Step-by-step walkthrough

  1. Clarify requirements and scope

    On a single machine, removing duplicate photos is straightforward: group files by byte size, hash the candidates, and delete the extra copies. At enterprise scale across cloud buckets, on-premises file servers, and thousands of customer organizations, the hard part is not finding duplicates — it is making sure a retry, a race condition, or a stale index never deletes a customer's last copy of a photo.

    Functional requirements

    • Detect exact duplicates: byte-for-byte identical photo files belonging to the same tenant (an isolated customer organization). Near-duplicates such as resized or re-compressed copies are handled separately as a user-assisted feature, never auto-deleted.
    • For each group of identical files, elect one surviving physical file (the keeper), update every logical reference (such as album entries or user folder paths) to point to the keeper, and remove the redundant physical copies. This indirection is called pointer semantics.
    • Make every removal reversible for a retention window via soft delete (hiding or moving bytes to a trash area before permanent deletion) and record every step in an immutable audit log.
    • Support an initial full scan, continuous incremental deduplication for newly uploaded files, and periodic background re-hashing.
    • Give operators a control plane for dry runs, sample inspection, approval gates, cancellation, and one-click restore.

    Non-functional requirements

    • Zero data loss: never delete the last surviving copy of a photo, and never replace a file with a keeper whose bytes differ. Missing a duplicate wastes a few cents of disk; a wrong deletion destroys customer data.
    • Strict tenant isolation: never deduplicate across tenants or allow one tenant's job to read another tenant's files.
    • Production safety: bound read throughput per storage location so background scanning never slows down live user traffic.
    • Crash-safe restarts: pausing, retrying, or restarting any worker or job must never apply an action twice or leave dangling pointers.

    Scale and topology assumptions

    Dimension Assumption used in this design
    Total files today 50M files initially, growing by 500K new uploads/day
    Average file size 3 MB (typical phone JPEG/HEIC), giving 50M x 3 MB = 150 TB total
    Storage locations ~10 locations: cloud object buckets in 2 regions + ~8 on-premises NAS (network-attached storage) file servers across 2 data centers
    Tenants ~2,000 organizations with skewed sizes; largest tenant owns 5M files
    Reference catalog A metadata database maps each logical photo_id to a physical file_id (built during the first scan if not already present)
    Redundancy rate Assumed 20% duplicate bytes (30 TB) until measured by the first dry run
    Intentional copies Backup and disaster-recovery (DR) buckets are marked excluded so deliberate durability copies are never treated as duplicates
  2. Back-of-the-envelope numbers and cost

    Doing the arithmetic first reveals what actually constrains the architecture: storage read bandwidth is the bottleneck, while CPU, network shuffle, and index memory are surprisingly small.

    1. Data volume and arrival rate
       Total bytes today          50,000,000 x 3 MB               = 150 TB
       New bytes per day          500,000 x 3 MB                  = 1.5 TB/day
       Average new-file rate      500,000 / 86,400 s              = ~5.8 files/s (~60 files/s at 10x peak)
    
    2. Full-scan wall-clock time (reading all 150 TB once)
       At 10 GB/s aggregate       150,000 GB / 10 GB/s            = 15,000 s  (~4.2 hours)
       At  2 GB/s throttled       150,000 GB /  2 GB/s            = 75,000 s  (~20.8 hours)
       -> Wall-clock time is governed by how fast we allow ourselves to read production storage.
    
    3. Hashing CPU cost
       Conservative software SHA-256 speed                        = ~0.5 GB/s per CPU core
       Total CPU work             150,000 GB / 0.5 GB/s           = 300,000 core-seconds (~83.3 core-hours)
       Cores needed at 10 GB/s    10 GB/s / 0.5 GB/s per core     = 20 CPU cores for ~4.2 hours
       Cores needed at  2 GB/s     2 GB/s / 0.5 GB/s per core     =  4 CPU cores for ~20.8 hours
    
    4. Network traffic leaving each storage site
       Compact hash record        ~120 B/file (tenant, file_id, size, version_token, 32-B hash, location)
       50,000,000 x 120 B                                         = 6 GB total across all sites
    
    5. Dedupe index size (at most 50M distinct contents)
       Relational table + B-tree  ~200 B/row x 50M                = ~10 GB (fits in RAM on one DB server)
       Catalog write rate in scan 50M / 75,000 s to 50M / 15,000 s = ~670 to ~3,330 rows/s (trivial in 1,000-row batches)
       Redis (if used)            ~140 B/key x 50M                = ~7 GB per copy (~14 GB with 1 replica)
    
    6. Periodic background re-hash (every file once every 90 days)
       150,000,000 MB / (90 x 86,400 s)                           = ~19.3 MB/s sustained
    

    Estimated cloud cost of one full scan vs. monthly savings

    Cost item Back-of-the-envelope estimate
    Hashing compute ~83 core-hours of SHA-256 + listing/I/O overhead = ~150-200 core-hours -> ~$10-$20 (even less on spot instances)
    Object GET requests 50M GET calls at ~$0.0004 per 1,000 requests = 50,000 x $0.0004 = ~$20
    Bucket listing Managed bucket inventory report (~$0.0025 per million objects) or ~50K LIST calls = < $1
    Cross-region egress (if central) Pulling 150,000 GB across regions at ~$0.02/GB = ~$3,000 -> avoided completely by hashing next to the data
    Monthly storage saved 20% of 150 TB = 30,000 GB; at ~$0.023/GB-month in cloud object storage = ~$690/month (higher on enterprise NAS)

    Because ~$700/month in cloud savings is modest compared to the business cost of losing one customer photo, every design choice below prioritizes safety and auditability over shaving hours off the scan.

  3. Control-plane API and data model

    Operators and tenant administrators interact with a small internal control-plane API. Write endpoints accept an idempotency_key — a unique client-generated token stored by the server so retrying a timed-out HTTP call returns the existing run instead of launching a duplicate run.

    POST /v1/dedupe/runs
      { "tenant_id": "t_123",
        "scope": { "locations": ["s3-use1-photos"], "prefixes": [] },
        "mode": "dry_run" | "execute",
        "delete_budget": { "max_files": 50000, "max_bytes": 200000000000 },
        "idempotency_key": "req_2026_11_30_t123" }
      -> 202 Accepted { "run_id": "r_789", "state": "LISTING" }
    
    GET  /v1/dedupe/runs/{run_id}
      -> { "state": "LISTING|HASHING|PLANNING|AWAITING_APPROVAL|EXECUTING|DONE|CANCELLED",
           "files_listed": 5000000, "bytes_hashed": 15000000000000,
           "duplicate_groups": 620000, "planned_ops": 980000, "done_ops": 980000,
           "verify_aborts": 0, "bytes_reclaimable": 2940000000000 }
    
    GET  /v1/dedupe/runs/{run_id}/report?cursor=...      paginated preview of keeper + duplicate pairs
    POST /v1/dedupe/runs/{run_id}:approve                { "approver": "alice", "second_approver": "bob" }
    POST /v1/dedupe/runs/{run_id}:cancel
    POST /v1/dedupe/restores                             { "op_id": "..." } or { "run_id": "r_789" } -> 202
    GET  /v1/files/{file_id}/dedupe-history              immutable audit trail for one file
    PUT  /v1/dedupe/policies/{tenant_id}                 opt-in flag, excluded_locations, retention_days
    

    Data model

    Each physical file carries a version_token — an opaque fingerprint of that file's storage state, such as an S3 ETag/object version ID or a NAS inode + size + mtime_ns tuple, which changes whenever the file is overwritten.

    locations(location_id PK, kind S3|GCS|NAS, site, durability_tier, excluded BOOL,
              max_read_bytes_per_s, max_read_ops_per_s)
    
    files(tenant_id, file_id) PK
      location_id, path, size, version_token,
      content_hash BYTEA(32) NULL, hash_key_version INT, hashed_at TIMESTAMP,
      state ACTIVE | DRAINING | SOFT_DELETED | PURGED | UNREADABLE,
      legal_hold BOOL
      INDEX (tenant_id, size)
      INDEX (tenant_id, content_hash)
    
    content_groups(tenant_id, content_hash) PK         -- the authoritative dedupe index
      keeper_file_id, keeper_version_token, member_count INT, updated_at TIMESTAMP
    
    photo_refs(tenant_id, photo_id) PK                 -- user-visible photos/albums -> physical blob
      file_id FK -> files, INDEX (tenant_id, file_id)
    
    dedupe_ops(op_id PK)                               -- op_id = SHA256(tenant_id, dup_file_id, dup_version_token)
      run_id, tenant_id, content_hash, dup_file_id, dup_version_token, keeper_file_id,
      state PLANNED | CLAIMED | VERIFIED | REPOINTED | SOFT_DELETED | PURGED | RESTORED | ABORTED,
      lease_owner, lease_expires_at, fencing_token BIGINT,
      moved_photo_ids UUID[], trash_location TEXT, error_code TEXT
    
    audit_events(event_id PK, op_id, run_id, tenant_id, actor, action,
                 before_json, after_json, code_version, ts)   -- append-only, mirrored to write-once storage
    

    Two schema invariants prevent subtle bugs later: - op_id excludes run_id: it hashes (tenant_id, dup_file_id, dup_version_token). If an incremental run and a batch scan both spot the same duplicate file version, they collide on the exact same op_id instead of scheduling two deletions. - DRAINING state and moved_photo_ids on dedupe_ops: marking a duplicate file DRAINING while moving its references prevents concurrent app requests from attaching new references right before storage soft-delete, and recording moved_photo_ids lets a restore put back the exact references that moved.

  4. High-level architecture

    Because reading all bytes takes 150 TB while hash records take only 6 GB, scanning and hashing run locally inside each storage region or NAS site, while grouping, planning, and safe execution use one central catalog.

     Storage sites (compute placed next to data; rate-limited per location)
     +-----------------------------------+    +-----------------------------------+
     | Cloud buckets (Region A / B)      |    | On-prem NAS servers (Site 1 / 2)  |
     |  - daily inventory + event stream |    |  - change journal / dir walker    |
     +-----------------+-----------------+    +-----------------+-----------------+
                       |                                        |
                       v                                        v
          [Site hash workers / Spark]              [Site hash workers / agent]
           read full bytes locally,                 read full bytes locally,
           emit 120-B hash records                  emit 120-B hash records
                       |                                        |
                       +-------------------+--------------------+
                                           | (~6 GB full scan; ~70 MB/day incremental)
                                           v
                 +---------------------------------------------------+
                 | Central Catalog DB (Postgres, partitioned by      |
                 | tenant_id): files, content_groups, photo_refs,    |<--> [Optional Redis read cache]
                 | dedupe_ops                                        |
                 +-------------------------+-------------------------+
                                           |
                                           v
                 [Planner] -- enforces exclusions, legal_hold, delete_budget, approval gate
                     |
                     | writes PLANNED rows in dedupe_ops, sharded by hash(tenant_id, content_hash)
                     v
                 [Executors] -- claim lease -> live verify -> repoint refs -> soft-delete -> audit
                     |
                     +---> [Versioned bucket delete marker / NAS .dedupe-trash]
                     |                     |
                     |                     +---> (after 30 days) [Purger] -> permanent delete
                     |
                     +---> [Immutable Audit Log (WORM bucket)] + [Metrics / Alerts / Restore API]
    

    Every file — whether discovered by the initial batch scan or a real-time upload event — passes through the same five stages: 1. List: build a manifest of (path, size, version_token) per location. 2. Hash locally: site workers read the file under per-location rate limits, verify byte counts, compute keyed SHA-256, and upsert (tenant_id, file_id) in files. 3. Elect keeper: upsert (tenant_id, content_hash) into content_groups so the first eligible copy atomically becomes the group's keeper. 4. Plan: create PLANNED rows in dedupe_ops for non-keeper copies, respecting excluded backup locations, legal holds, and per-run budgets. 5. Execute & purge: executors re-verify live bytes, atomically re-point photo_refs to the keeper, soft-delete the redundant file, and let a separate purger hard-delete after 30 days.

  5. Deep dive 1: Dedupe index store, Redis schema, sizing, and eviction

    The dedupe index maps (tenant_id, content_hash) -> keeper_file_id and must decide atomically who wins when two identical files arrive at the same millisecond.

    Store option Atomicity & durability Footprint at 50M keys Best when
    Partitioned Postgres (chosen authority) Synchronous WAL durability; INSERT ... ON CONFLICT (tenant_id, content_hash) DO NOTHING elects a keeper, and one ACID transaction updates photo_refs, files, and dedupe_ops together ~10 GB including B-tree index (fits in RAM on one mid-size instance) 50M-200M files; ~670-3,330 batched upserts/s during full scan and ~6-60/s steady state
    Redis Cluster Sub-millisecond SET key val NX; asynchronous replication, so a primary crash before replication can lose a newly elected keeper ~7 GB primary + ~7 GB replica + overhead (~20-24 GB cluster RAM) High-QPS synchronous upload-time dedupe checks, or as a read-through cache in front of Postgres
    DynamoDB / ScyllaDB / Cassandra Durable horizontal scale; conditional writes (attribute_not_exists / IF NOT EXISTS) elect a keeper, but cross-table reference updates require a multi-step saga (a chain of separate writes with compensating rollbacks) Disk-backed; scales effortlessly past billions of keys 500M-10B+ files or active-active multi-region writes
    Pure Spark shuffle (no online store) Grouping happens only inside a batch GROUP BY 0 GB online One-off offline cleanup with no incremental pipeline

    Why Postgres is the source of truth here, and how Redis fits in: at 50M files, the entire index is ~10 GB, and steady-state incremental traffic is ~6-60 files/s. Using Postgres avoids split-brain consistency bugs between a KV index and the photo_refs table. If we later add synchronous upload-time dedupe at tens of thousands of QPS, we place Redis Cluster in front as a read-through cache (or at 1B+ files, shard content_groups onto DynamoDB).

    Redis key schema, memory sizing, and eviction (if deployed)

    Key:    dg:<tenant_id>:<32 raw bytes of HMAC-SHA256>     (~43 bytes total)
    Value:  <16 raw bytes of keeper file_id UUID>            (16 bytes)
    
    • Binary keys, not hex: storing 32 raw digest bytes instead of a 64-character hex string saves 32 bytes per key (1.6 GB across 50M keys before replication).
    • Never wrap tenant_id in {...}: in Redis Cluster, curly braces define a hash tag — a rule forcing Redis to route every key with the same {...} substring onto the exact same shard. Writing dg:{t_123}:<hash> would dump all 5M keys of our largest tenant onto a single node. Leaving braces off hashes the entire key evenly across all 16,384 cluster slots.
    • Optional listpack bucketing: grouping keys into small Redis hashes (HSET dg:<tenant_id>:<first_3_hash_bytes> <remaining_29_bytes> <16B_file_id>) keeps ~100-250 entries per bucket so Redis stores each bucket as a listpack (a flat, pointer-free byte array), cutting per-key dictEntry pointer overhead by ~50%.
    • Memory sizing: 50M keys x ~140 B (key + value + jemalloc/dictEntry overhead) = ~7 GB for primaries. In a 6-node cluster (3 primaries + 3 replicas on 8 GB machines), each node holds 7 GB / 3 = ~2.33 GB of live keys. Set maxmemory = 4 GB per node (24 GB cluster cap) so background snapshot fork() calls have ~4 GB of free RAM per host for OS copy-on-write (duplicating memory pages modified while a snapshot is being written to disk). Alert at 75% of maxmemory.
    • Eviction policy: if Redis is a read-through cache backed by Postgres, allkeys-lru (evicting least-recently-used keys when full) is safe because a cache miss falls back to Postgres and executors always verify against Postgres before deleting. If Redis were ever used standalone without a DB backing it, noeviction is mandatory — evicting a keeper entry would let a second copy claim keeper status and confuse concurrent workers.
  6. Deep dive 2: Batch scan-and-hash pipeline, partitioning, and locality

    Stage 1 — Listing without hammering storage: for cloud buckets, consume daily S3/GCS Inventory Parquet files rather than issuing 50,000 sequential LIST calls; for NAS servers, run a local agent that walks directory trees in parallel with bounded I/O concurrency. Write a partitioned manifest of (location_id, tenant_id, file_id, path, size, version_token).

    Stage 2 — Hash every file vs. pre-filtering by size and partial hash: On a single laptop, we filter by (tenant_id, size) and a 128 KB head/tail hash before full hashing. At our scale: - In a 5M-photo tenant where files sit between 1 MB and 6 MB (~5M distinct byte counts), each file's chance of sharing its exact byte count with at least one unrelated photo by pure luck (Poisson occupancy with average lambda = 5M / 5M = 1) is 1 - 1/e = ~63.2%. So size filtering eliminates only ~37% of files in big tenants! - Partial hashing (first + last 64 KB) reads 50M x 128 KB = 6.4 TB plus full reads of all ~20% duplicates and their keepers (~50-60 TB total), saving ~60% of bytes on day 1, but leaves singletons unhashed in files, forcing random lazy reads later whenever a new upload matches an old file's byte size. - Because reading all 150 TB locally finishes in 4-21 hours and populates content_hash for 100% of files (making every future incremental check a single O(1) index lookup), hash every file on local cloud/NAS storage, and reserve (size -> partial hash -> full hash) strictly for high-cost tiers such as archival storage or cross-cloud mounts.

    Partitioning and data locality

    Site manifest  -->  Bin-pack by BYTES (~10 GB/task -> ~15,000 map tasks, pinned to same site/region)
                   -->  Local workers stream bytes + compute HMAC-SHA256 (throttled per location)
                   -->  Emit 120-B records (6 GB total) -> Shuffle by hash(tenant_id, content_hash)
                   -->  Batch-upsert files & content_groups in Postgres ( NEVER delete inside Spark! )
    
    • Bin-pack tasks by byte sum (~10 GB/task), not file count: partitioning by file count or folder lets one directory full of 50 MB raw camera bursts become a 2-hour straggler (a single slow task that holds up job completion).
    • Compute next to data: Spark/worker pools run in the exact cloud region or NAS data center holding each location's bytes, keeping 150 TB on free local network links and sending only 6 GB of compact hash records centrally.
    • Defensive hashing inside each task:
      1. Verify bytes_actually_read == listed_size. A network drop that truncates a stream (short read) must emit an error, never a digest — otherwise thousands of truncated zero-length or partial streams hash to the same digest and look like duplicates!
      2. Skip 0-byte files (deleting them saves 0 bytes and risks breaking placeholder files).
      3. Re-stat version_token after reading; if the file changed mid-read, skip and re-queue.
      4. Use HMAC-SHA256, never MD5 or SHA-1 (both have public collision attacks allowing an attacker to upload two different images with matching digests). Across n = 50M honest files, the birthday-bound probability of an accidental SHA-256 collision is n^2 / 2^257 = ~10^-62.
  7. Deep dive 3: Idempotency, race conditions, and crash-safe execution

    Distributed workers crash, pause during garbage collection, and run speculative execution (launching a backup copy of a slow task). True "execute once" hardware does not exist; instead we achieve exactly-once effect by combining at-least-once retries with idempotent state transitions (operations where repeating a step produces the exact same final state).

    How two overlapping workers could destroy data — and the 4 defenses that make it impossible Suppose Batch Run A and Incremental Run B both see identical files X and Y. If Run A elects X as keeper and deletes Y while Run B elects Y as keeper and deletes X, every copy vanishes. We prevent this with four independent layers: 1. Single persisted keeper: content_groups elects a keeper once via INSERT ... ON CONFLICT DO NOTHING. Runs never pick their own keeper in memory; they read content_groups.keeper_file_id. 2. Deterministic keeper tie-breaker: when populating a group from batch candidates, rank by (legal_hold DESC, durability_tier DESC, created_at ASC, file_id ASC). 3. Partitioned single-threaded group execution: executors consume dedupe_ops partitioned by hash(tenant_id, content_hash), so two executors never mutate the same duplicate group concurrently. 4. Leases with fencing tokens: each executor claims an op lease that increments a monotonic integer fencing_token. Every catalog write includes WHERE op_id = ? AND fencing_token = ? (compare-and-set, updating only if no newer worker took over), so a paused "zombie" worker wakes up and gets rejected immediately.

    Crash-resumable, race-free executor logic

    Notice two subtle traps in naive deletion code: first, if a user attaches a new album reference to dup after references are moved but before dup is soft-deleted, that reference breaks; second, if an executor crashes right after moving references, a retry must resume at storage soft-delete rather than wiping moved_photo_ids. Solving both cleanly:

    def execute_op(op, catalog, storage, audit):
        """Safely verify, drain references, and soft-delete one duplicate file."""
        # Phase 1: Live verification (runs only when the op was just CLAIMED).
        if op.state == "CLAIMED":
            dup = catalog.get_file(op.tenant_id, op.dup_file_id)
            keeper = catalog.get_file(op.tenant_id, op.keeper_file_id)
            group = catalog.get_group(op.tenant_id, op.content_hash)
    
            if dup.tenant_id != keeper.tenant_id:
                return catalog.abort(op, audit, "cross_tenant_mismatch")
            if group.keeper_file_id != keeper.file_id or dup.file_id == keeper.file_id:
                return catalog.abort(op, audit, "keeper_changed")
            if dup.legal_hold or dup.state != "ACTIVE" or keeper.state != "ACTIVE":
                return catalog.abort(op, audit, "ineligible_file_state")
            if storage.read_version_token(dup) != op.dup_version_token:
                return catalog.abort(op, audit, "dup_modified_since_hash")
            if not storage.verify_identical_bytes(dup, keeper):
                return catalog.abort(op, audit, "live_content_mismatch")
    
            catalog.advance_cas(op, from_state="CLAIMED", to_state="VERIFIED")
    
        # Phase 2: Atomic DB repoint + DRAINING lock so no new refs attach to dup.
        if op.state == "VERIFIED":
            with catalog.transaction() as tx:
                # Lock both file rows in file_id order to prevent deadlocks.
                keeper_row, dup_row = tx.lock_pair_ordered(
                    op.tenant_id, op.keeper_file_id, op.dup_file_id
                )
                if keeper_row.state != "ACTIVE" or dup_row.state != "ACTIVE":
                    return tx.abort(op, audit, "concurrent_state_change")
    
                tx.set_file_state(op.tenant_id, op.dup_file_id, "DRAINING")
                moved = tx.repoint_refs(
                    op.tenant_id, from_file=op.dup_file_id, to_file=op.keeper_file_id
                )
                tx.advance_cas(
                    op, from_state="VERIFIED", to_state="REPOINTED", moved_photo_ids=moved
                )
            audit.write(op, "REPOINTED", moved_photo_ids=moved)
    
        # Phase 3: Idempotent storage soft-delete (safe to repeat after a crash at REPOINTED).
        if op.state == "REPOINTED":
            dup = catalog.get_file(op.tenant_id, op.dup_file_id)
            storage.soft_delete_idempotent(dup, op.op_id)
            with catalog.transaction() as tx:
                tx.set_file_state(op.tenant_id, op.dup_file_id, "SOFT_DELETED")
                tx.advance_cas(op, from_state="REPOINTED", to_state="SOFT_DELETED")
            audit.write(op, "SOFT_DELETED")
    
  8. Verification, canarying, soft delete, incremental runs, and scrubbing

    Live verification before deletion: a bug in path parsing or a stale migration table is billions of times more likely than a SHA-256 collision. Before moving pointers, verify_identical_bytes checks live HEAD/stat tokens, verifies the keeper is readable on a tier at least as durable as the copy, and either compares raw streams byte-for-byte (same site) or computes fresh local SHA-256 digests at each site (cross-site, sending 32 bytes over WAN). Re-reading ~20% duplicates (~30 TB) + keepers once per run is cheap insurance against stale metadata.

    Canarying and automatic safety brakes - Dry-run everywhere first, surfacing reclaimable bytes and random visual side-by-side samples for human spot checks. - Gradual rollout: internal dogfood tenant -> 1% of opted-in tenants on a single bucket with a tiny delete_budget -> hold for a full 30-day retention window (since missing-photo tickets arrive weeks later) -> 10% -> 50% -> 100%. - Delete budget + circuit breaker: cap any unapproved run at min(5% of tenant files, 1 TB), and trip an automatic circuit breaker (an automated shutoff switch) that pauses the entire run if verify_aborts / attempted_ops > 0.1%, plus a global kill switch stopping all executors in seconds.

    Soft delete, restore, and immutable audit - Versioned cloud buckets: standard DeleteObject writes a reversible delete marker while keeping the noncurrent version intact; a bucket lifecycle policy purges noncurrent versions after 30 days. - NAS volumes: rename() moves the file into .dedupe-trash/<op_id> on the same filesystem — an O(1) atomic metadata operation that copies zero bytes. A purger removes trash entries 30 days after SOFT_DELETED. - Restore: puts the file back from .dedupe-trash (or deletes the S3 delete marker), updates moved_photo_ids back to dup_file_id, sets files.state = ACTIVE, and logs RESTORED. - Audit: every transition writes who, what, version tokens, digest, moved_photo_ids, and code SHA to an append-only table mirrored to WORM (write-once-read-many) object-lock storage so even a compromised admin credential cannot erase history.

    Incremental pipeline and 90-day scrubbing - Incremental arrivals (~6 files/s avg, ~60/s peak): bucket ObjectCreated events and NAS change journals feed a per-site queue, backed by a nightly inventory reconciliation (since event notifications can occasionally drop) with a safety-margin overlap for clock skew. New duplicates wait a 24-hour grace period before execution so temporary uploads and active user edits settle first. - 90-day periodic re-hash (~19.3 MB/s): deduplication eliminates accidental copy redundancy, meaning popular photos now rely on one keeper blob. Keepers must sit on storage with hardware redundancy (erasure coding — striping data with parity blocks across multiple drives — or multi-AZ replication), and scrubbing every keeper every 90 days catches: 1. Bit rot (silent disk media corruption): if a keeper's live digest changes, page immediately and auto-heal from soft-deleted copies or backups. 2. Stealth in-place edits on NAS where backup/sync tools overwrite bytes and reset mtime (touch -r), fooling inode + mtime. 3. Key rotation: smoothly upgrading hash_key_version in the background.

  9. Fault tolerance, backpressure, monitoring, security, and trade-offs

    Fault tolerance & backpressure - Worker/executor crashes: Spark retries failed hash tasks idempotently; completed manifest shards are checkpointed; expired executor leases hand ops cleanly to a peer with an incremented fencing_token. Unreadable individual files are retried with exponential backoff, marked UNREADABLE, and skipped without failing the shard. - Catalog outage: fail closed — stop planning and deletion immediately while site hashers buffer records on disk. - Storage backpressure: enforce per-location token buckets (rate limiters that refill bytes/s and ops/s budgets at a steady rate, e.g., 20% of NAS spare bandwidth by day, 50% overnight) combined with AIMD (additive increase, multiplicative decrease) adaptive throttling: if storage read p99 latency breaches its target or S3 returns 503 SlowDown, immediately halve concurrency; when healthy, step concurrency up by 5% per minute. Use weighted fair queuing across tenants so one 5M-file scan cannot starve small tenants' incremental queues.

    Key operational metrics and alerts

    Metric Why we watch it / when to page
    Bytes/s & files/s hashed per location, storage p99 latency Confirms scan progress and verifies throttling protects live traffic
    Verification abort rate (verify_aborts / ops) Page immediately above 0.1% — means catalog metadata disagrees with live storage
    Planned & executed deletes vs. tenant delete_budget Catches runaway configuration or policy bugs before scale
    Keeper scrub hash mismatches Page immediately on > 0 — silent bit rot on a keeper copy
    Restore rate, queue oldest-message age, short-read count Lagging correctness indicator, incremental backlog health, network/NAS health

    Security and multi-tenant isolation - Per-tenant keyed hashing (HMAC-SHA256(tenant_secret, file_bytes)): global cross-tenant deduplication creates a textbook side-channel leak — an attacker uploads a sensitive target photo and checks quota or timing to learn whether another company already stores it. Scoping content_groups by tenant_id and keying digests with per-tenant KMS secrets ensures digests cannot even be compared across tenants if the index leaks. - Split least-privilege IAM roles: - ScannerRole: read-only GetObject / ListBucket scoped via short-lived credentials to one tenant's prefix. - ExecutorRole: update catalog + s3:DeleteObject (adds reversible delete marker only) / move to .dedupe-trash; cannot permanently purge. - PurgerRole: only role granted s3:DeleteObjectVersion / .dedupe-trash unlink(), restricted to items past the 30-day retention window. - Dual human approval required for any run exceeding its delete budget or any full-run bulk restore.

    Summary of core trade-offs - Safety vs. immediate savings: live re-reads, pointer semantics, and 30-day soft delete delay reclaiming ~$700/month of space, in exchange for making wrong deletions observable and reversible. - Partitioned Postgres vs. Redis/DynamoDB as authority: gives single-transaction ACID updates across pointers and ops up to hundreds of millions of files, trading away multi-billion-key horizontal write scale we do not yet need. - Full local hashing vs. partial-hash pre-filtering: reads 150 TB once locally so every future incremental check is O(1), avoiding cross-region $3,000 transfer fees and random lazy reads. - Per-tenant HMAC dedupe vs. global dedupe: gives up cross-customer duplicate savings to eliminate side-channel leaks and cross-tenant blast radius.

Intuition & how it works

Imagine managing 10 regional photo archives holding 50 million printed photographs, where customers browse albums made of index cards that point to physical prints on warehouse shelves. You want to reclaim shelf space from identical prints without ever throwing away a customer's only copy. Instead of letting warehouse clerks walk the aisles and shred duplicates on sight, clerks at each building stay local, compute a tamper-proof cryptographic fingerprint (content hash — a fixed-size 32-byte summary of a file's exact bytes) for every print, and send only thin 120-byte index slips to one central catalog. For each group of identical prints within the same customer organization (tenant), the catalog elects a single surviving keeper print, atomically updates every album card to point at that keeper (pointer semantics), and moves the redundant prints into a 30-day locked basement bin (soft delete) before permanently recycling them.

A naive port of the single-machine script — reading files into a central Spark cluster and calling delete() inside worker tasks — fails dangerously at scale. Pulling 150 TB of raw photos across cloud regions costs ~$3,000 in transfer fees per scan and saturates live storage bandwidth. Worse, distributed workers retry timed-out tasks and overlap with incremental scans: if Worker A elects File 1 as keeper and deletes File 2 while Worker B elects File 2 and deletes File 1, both copies vanish forever. Separating local stateless hashing from centrally serialized, lease-fenced pointer updates and soft deletion makes retries harmless and keeps 99.99% of bytes inside each storage site.

Walk through a tiny example for tenant t_1 with three 3 MB files: f_1 and f_2 (byte-identical beach photos referenced by albums A and B) and f_3 (a portrait):

1. Local hash:   Site workers stream all 3 files locally -> f_1 and f_2 both yield digest H_beach; f_3 yields H_port.
2. Elect keeper: Catalog upserts (t_1, H_beach) into content_groups -> f_1 wins keeper; f_2 becomes a PLANNED op.
3. Live verify:  Executor claims f_2's op with fencing_token=7, checks live version tokens, and verifies f_2 == f_1.
4. Drain & move: One DB transaction locks f_1 and f_2, marks f_2 DRAINING, repoints album B -> f_1, saves moved=[B].
5. Soft-delete:  f_2 moves to .dedupe-trash (or gets an S3 delete marker) for 30 days, then Purger frees the 3 MB.

Key trade-offs

  • Safety layers vs. immediate storage savings. Re-reading duplicates right before deletion, keeping a 30-day soft-delete window, and enforcing per-run delete budgets (caps on how many files or bytes one run may remove without human sign-off) consume extra reads and delay savings by a month. At 150 TB with 20% redundancy, 30 TB of cloud object storage costs ~$700/month, whereas losing a single irreplaceable photo permanently damages customer trust.
  • Pointer semantics vs. direct in-place file deletion. Mapping logical photo_id references to physical file_id blobs means users never see broken album entries, and a user deleting one album reference never deletes bytes still needed by another album. It requires maintaining a reference catalog; direct file deletion avoids that table but exposes every bug immediately to end users.
  • Partitioned relational DB vs. distributed KV store for the dedupe index. At 50M groups (~10 GB), one Postgres database partitioned by tenant_id lets an executor lock file rows, re-point photo_refs, and advance dedupe_ops in a single ACID transaction (an all-or-nothing database update). DynamoDB or Cassandra scales to billions of entries, but splits reference updates and op state across tables into a saga (a multi-step workflow requiring compensating rollbacks). Redis Cluster offers sub-millisecond reads (SET ... NX), but uses asynchronous replication (confirming writes before replicas receive them), making it ideal as an optional read cache rather than the sole source of truth.
  • Full-byte hashing vs. size and partial-hash pre-filtering. Reading all 150 TB once locally (4-21 hours) populates every file's hash up front so every future upload does one O(1) index lookup. Pre-filtering by byte size and a 128 KB head/tail hash cuts day-one reads to ~50-60 TB, but in a 5M-file tenant ~63% of unique 1-6 MB photos share an exact byte size by chance (1 - 1/e), and unhashed singletons force random lazy reads later. Reserve pre-filtering for archival or high-egress storage tiers.
  • Per-site local workers vs. one central cluster. Running hashers inside each cloud region and NAS site sends 6 GB of metadata instead of 150 TB of pixels (~$3,000 in cross-region transfer fees plus WAN bottlenecks), trading operational simplicity for deploying lightweight worker pools per site.
  • Event-driven incremental dedupe vs. periodic full listing. Bucket event notifications detect new uploads in seconds but can occasionally drop messages; combining real-time queues with a nightly inventory reconciliation gives both low latency and 100% completeness.
  • Per-tenant keyed dedupe vs. global cross-tenant dedupe. Deduplicating across tenants reclaims slightly more space, but opens a side-channel attack (an indirect leak where an attacker tests whether another customer holds a specific photo by watching upload speed or quota) and couples customer lifecycles. Scoping by tenant_id with HMAC-SHA256 (hashing combined with a per-tenant secret key) eliminates both risks.

Common mistakes

  • Deleting files directly inside Spark or MapReduce tasks. Batch frameworks retry slow or failed tasks and run speculative execution (duplicate backup tasks); executing side effects inside map/reduce tasks causes double deletions or half-finished pointer updates. Batch jobs should only emit metadata and plans.
  • Re-computing the keeper independently in each run. If an overlapping batch scan and incremental worker each pick a keeper in memory without consulting a single persisted content_groups row, one can delete copy X while the other deletes copy Y.
  • Leaving a race window between re-pointing references and soft-deleting bytes. If dup stays ACTIVE after repoint_refs commits, a concurrent request can attach a new album reference to dup milliseconds before storage deletes it. Locking dup and transitioning it to DRAINING inside the same transaction closes that gap.
  • Hashing truncated ("short") reads or using MD5/SHA-1. If a dropped NAS socket returns 0 bytes or half a file and the worker hashes whatever arrived, unrelated files get identical hashes and get queued for deletion. Always verify bytes_read == expected_size, skip 0-byte files, and use SHA-256 (MD5 and SHA-1 both suffer from practical collision attacks).
  • Misconfiguring Redis Cluster hash tags or eviction. Putting braces around {tenant_id} in Redis keys forces an entire 5M-file customer onto one shard, and leaving volatile-lru or allkeys-lru enabled when Redis is treated as authoritative silently evicts keeper records.
  • Deduplicating backup/DR buckets or forgetting keeper bit rot. Deleting intentional disaster-recovery copies destroys durability, and once duplicates are removed, silent media corruption (bit rot) on the single keeper destroys the photo unless keepers sit on redundant storage and undergo 90-day hash scrubbing.
  • Scanning production storage unthrottled or hard-deleting without WORM audit logs. Saturating NAS IOPS causes customer-facing outages, and hard-deleting without a 30-day trash window and WORM (write-once-read-many) audit logs makes bugs unrecoverable.

Follow-up questions

  • How would your architecture change if product asked to detect visually similar near-duplicates (such as resized, cropped, or re-compressed images)? Compute a 64-bit perceptual hash (such as dHash or pHash, which summarizes low-frequency visual structure rather than exact file bytes) or a compact vision-model embedding per photo, and search within the same tenant using Hamming distance (counting differing bits between two 64-bit hashes) or an approximate nearest-neighbor index. Because resized or cropped images are not identical — one may have higher resolution or an intentional edit — never auto-delete near-duplicates; instead, surface high-precision groups in the UI, highlight the highest-resolution photo as the recommended keeper, and require user confirmation.
  • What if photos reside directly on POSIX file servers accessed by path, with no database reference layer between users and files? Without a database indirection layer, removing a file path breaks scripts or users opening that path directly. On the same filesystem, you can replace duplicates with POSIX hard links (multiple directory entries pointing to one shared inode, though in-place edits and file permissions/ownership are shared across all linked names) or, much better on XFS/Btrfs, copy-on-write reflinks (cp --reflink=always, which share physical disk extents while keeping independent permissions, timestamps, and safely splitting blocks if either file is later edited). The verify-before-act executor, .dedupe-trash quarantine, inode + size + mtime_ns version checks, and WORM audit trail remain identical.
  • After a large production cleanup run finishes, how do you verify with high confidence that zero unique customer photos were lost? Run an automated post-run reconciliation before any 30-day purge is unlocked: verify that every SOFT_DELETED op's keeper_file_id is ACTIVE, readable, matches the group's content_hash on a fresh read, and currently holds every reference recorded in moved_photo_ids. Pair that automated 100% check with stratified human visual inspection of a few hundred sampled (keeper, soft_deleted_dup) pairs and compare restore rates and support tickets on canary tenants against an untouched holdout group across the full retention window.

Follow-up questions

Similar questions

More Abnormal Security interview questions

All 2 Abnormal Security questions →