Content-Addressable Storage with Reference Counting for Media Files in Messaging Apps

    This article explains how messaging applications can deduplicate media files using content-addressable storage and reference counting. It covers the core data model, write and delete paths, concurrency control, delayed garbage collection, privacy considerations for showing usage counts, side-channel risks in cross-user deduplication, and practical observability metrics.

    Introduction

    In instant messaging and collaboration applications, users frequently forward the same image, video, or file. If every forward stores a full copy on the server, storage costs grow linearly with the number of forwards. When the same content is sent to multiple conversations, upload bandwidth, backup volume, and synchronization latency also increase.

    Deduplicated storage solves the core problem by keeping only one physical copy of identical content while each conversation holds a logical reference. Users see independent message attachments, but the system actually occupies only one copy of the data.

    Achieving this requires three cooperating components:

    • Content fingerprint: a stable, comparable digest computed for each piece of content.
    • Reference tracking: records how each message or conversation uses the content.
    • Reclamation mechanism: safely frees physical storage when no references remain.

    Core Idea: Content-Addressable Storage

    Content-Addressable Storage (CAS) uses the digest of the content as the storage key. A common approach is to compute the file digest using SHA-256. Collision probability for cryptographic hashes is negligible in practice, but two points still deserve attention:

    1. Even when digests match, verify file size and type to avoid misclassification due to implementation errors.
    2. For security-sensitive scenarios, perform a byte-level comparison on a deduplication hit, or enable integrity checks at the storage layer.

    The benefit of content addressing is that the same byte sequence always maps to the same key, regardless of how many times it is uploaded. This turns a deduplication check into a simple index lookup without scanning raw data.

    Data Model Design

    The system typically splits storage into two core tables: a physical blob table that records the actual data location and reference count, and a reference table that tracks the relationship between each message and the physical blob.

    1. -- Physical blob: one digest corresponds to one copy of the actual data
    2. CREATE TABLE blob (
    3. digest CHAR(64) PRIMARY KEY, -- content digest
    4. size BIGINT NOT NULL, -- byte size
    5. mime_type VARCHAR(128), -- content type
    6. ref_count INT NOT NULL DEFAULT 0, -- number of valid references
    7. created_at TIMESTAMP NOT NULL
    8. );
    9. -- Reference: each message attachment corresponds to one row
    10. CREATE TABLE file_ref (
    11. ref_id BIGINT PRIMARY KEY,
    12. digest CHAR(64) NOT NULL REFERENCES blob(digest),
    13. owner_id BIGINT NOT NULL,
    14. conversation_id BIGINT NOT NULL,
    15. message_id BIGINT NOT NULL,
    16. created_at TIMESTAMP NOT NULL
    17. );
    18. CREATE INDEX idx_file_ref_digest ON file_ref(digest);

    There are two important design points here. First, ref_count is a denormalized field used to quickly decide whether a blob can be reclaimed. It must remain consistent with the actual row count in file_ref, so both writes and deletes must be performed inside the same transaction. Second, file_ref stores owner_id and conversation_id, which play a key role in access control later.

    Write Path and Concurrency Control

    The upload flow should follow this order:

    1. Compute the digest in a streaming fashion to avoid loading large files into memory.
    2. Query the physical blob inside a transaction and lock the row.
    3. If the blob does not exist, write the object to storage and insert a record.
    4. Increment the reference count, insert the reference record, and commit the transaction.

    Below is a vendor-agnostic example implementation. db and blob_store are abstract interfaces that should be replaced with your database access layer and storage client in a real project.

    1. import hashlib
    2. CHUNK_SIZE = 1 << 20 # 1 MiB
    3. def compute_digest(stream) -> str:
    4. """Compute SHA-256 digest in a streaming fashion; memory usage is independent of file size."""
    5. hasher = hashlib.sha256()
    6. for chunk in iter(lambda: stream.read(CHUNK_SIZE), b""):
    7. hasher.update(chunk)
    8. stream.seek(0)
    9. return hasher.hexdigest()
    10. def save_reference(db, blob_store, stream, owner_id, conversation_id, message_id):
    11. digest = compute_digest(stream)
    12. with db.transaction():
    13. blob = db.blobs.get_for_update(digest)
    14. if blob is None:
    15. size = blob_store.put(digest, stream)
    16. try:
    17. db.blobs.insert(digest=digest, size=size, ref_count=0)
    18. except db.UniqueViolation:
    19. # Another request has already inserted the same digest; reuse its record
    20. pass
    21. db.blobs.increment_ref(digest)
    22. return db.refs.insert(
    23. digest=digest,
    24. owner_id=owner_id,
    25. conversation_id=conversation_id,
    26. message_id=message_id,
    27. )

    The most common concurrency problem is two requests uploading the same content at the same time. The example handles this race using a unique constraint and row locking. If a unique constraint violation occurs, another transaction has already created the physical blob, and the current transaction simply reuses it. A leftover unreferenced copy may remain in object storage; this is handled by the reclamation process later.

    Deletion and Delayed Reclamation

    When a message is deleted, the system only needs to remove the corresponding reference record and decrement the count on the physical blob. The physical data itself must not be deleted immediately, for two reasons:

    • Other conversations may still hold references to the same content.
    • There might be uncommitted transactions in the write path; immediate deletion could cause a race condition.

    When the count reaches zero, the system should place the digest into a reclamation queue with a grace period. After the grace period expires, the reclamation task verifies that the count is still zero before actually deleting the object.

    1. from datetime import datetime, timedelta
    2. GRACE_PERIOD = timedelta(days=7) # adjust based on data recovery requirements
    3. def delete_reference(db, ref_id):
    4. with db.transaction():
    5. ref = db.refs.get(ref_id)
    6. db.refs.delete(ref_id)
    7. db.blobs.decrement_ref(ref.digest)
    8. blob = db.blobs.get(ref.digest)
    9. if blob.ref_count == 0:
    10. db.gc_queue.enqueue(
    11. digest=ref.digest,
    12. eligible_after=datetime.utcnow() + GRACE_PERIOD,
    13. )

    Because the counter can drift due to abnormal interruptions, the system should periodically run a reconciliation job. This job can count the actual number of rows in file_ref for each digest and compare it with ref_count. When a mismatch is found, correct the counter based on the reference table and log an alert for root-cause analysis.

    Showing Reference Counts to Users: Visibility and Privacy

    Letting users see how many conversations use the same file can reduce concerns about storage growth and helps users understand that forwarding does not copy the file’s payload itself. However, reference information is also data, and careless presentation can cause privacy leaks.

    The main risks include:

    • Global count leaks propagation scope: if the count includes references from other users, an attacker can infer how widely a piece of content has been shared.
    • Conversation list leaks others’ information: listing “which conversations use this file” may expose the existence of other users’ conversations.
    • Time and ordering information: reference creation times may reveal others’ chat activity patterns.

    The recommended principle is minimal disclosure. A display endpoint should only count and return references that the calling user is authorized to access. For example:

    1. def visible_references(db, digest, viewer_id):
    2. refs = db.refs.list_by_digest(digest)
    3. mine = [r for r in refs if r.owner_id == viewer_id]
    4. return {
    5. "usage_count": len(mine),
    6. "conversation_ids": [r.conversation_id for r in mine],
    7. }

    With this design, users see usage within their own scope. For references that do not belong to the caller, the system only needs to maintain correct storage structures without exposing any details.

    Side-Channel Risks in Cross-User Deduplication

    If deduplication spans different users, the risk increases further. An attacker can first upload a known piece of content and observe the server’s response or timing. If the system reports an “instant upload” (deduplication hit), the attacker can infer whether another user already holds the same content. This is called a deduplication side-channel attack and is a well-known risk in file storage systems.

    Three common mitigations exist:

    1. Per-tenant hashing space isolation: apply a keyed HMAC to the content digest, with the key separated by tenant or user, so that digests differ between users and cross-user existence detection is prevented.
    2. Uniform response behavior: return the same status code and similar processing latency regardless of whether deduplication hits.
    3. Deduplication within the same user only: sacrifice some storage efficiency for stronger isolation.
    1. import hmac
    2. import hashlib
    3. def scoped_digest(content_digest: str, tenant_key: bytes) -> str:
    4. """Apply an HMAC with a tenant-specific key to the content digest to prevent cross-tenant existence probing."""
    5. return hmac.new(tenant_key, content_digest.encode(), hashlib.sha256).hexdigest()

    The tenant_key should be stored in a key management service, not in code or logs. Which option to choose depends on the relative priority of storage cost versus privacy in your business.

    Observability Metrics

    After enabling deduplication, monitor the following metrics continuously:

    • Deduplication ratio: ratio of logical bytes used to physical bytes stored.
    • Instant upload hit rate: proportion of upload requests that hit an existing physical blob.
    • Counter drift: the difference between ref_count and the actual reference count found during reconciliation.
    • Reclamation queue length and throughput: indicates whether the grace period is configured reasonably.

    Reasonable thresholds for these metrics must be derived from your own business baseline; avoid directly adopting values from other systems.

    Implementation Checklist

    • Digest algorithm is fixed to a cryptographic hash, and the algorithm version is recorded for future migration.
    • Physical blob and reference writes are in the same transaction, keeping the counter and reference table consistent.
    • Deletion path only decrements the counter; reclamation requires a grace period and a second confirmation.
    • A scheduled reconciliation job is in place and alerts on counter drift.
    • Display endpoints only return references visible to the caller.
    • Cross-user deduplication has been assessed for side-channel risks, and an isolation solution has been chosen.
    • Keys are managed by a key management service; code and logs contain no sensitive values.

    Conclusion

    The main benefits of reference-counted deduplication come from content addressing and transactional consistency, while user experience and privacy protection depend on how much reference information is disclosed. Engineering efforts should first ensure correct counting and safe reclamation, then decide how much information to show to users, and clearly define the boundary between risk and benefit for cross-user deduplication.