DEV Community

CelesteRaine1783
CelesteRaine1783

Posted on

How to Bound Node.js Image Review Retention — Notify Uploaders After 2 Outcomes

A logistics uploader needs delivery evidence reviewed, text extracted with OCR, and a decision returned before uploading the same photo becomes the easiest way to ask what happened. Start with private images and queued references. The bill contains retained image bytes, image transfers, processing, queue operations, and notifications. In a planning workload of 10,000 photos at 4 MB each, a full review pass transfers 40 GB; a proposed 0.4 MB derivative transfers 4 GB. Those are chosen inputs, not measured compression results. Actual rates determine the dominant invoice line, but image bytes are the first term to quantify here.

TL;DR: In a Node.js/Express application, queue review work, record the moderator and reason, then publish or reject and notify the uploader in both cases. Use a smaller review image only after checking required text against the original, keep the original private for a declared evidence window, and delete it deliberately afterward.

Bytes accumulate quietly.

A reviewer may need the delivery scene while OCR needs fine print on a shipment label. A preview can satisfy the first requirement and destroy the second. The storage decision therefore starts with what evidence must remain readable, rather than an unsupported promise that a different provider will improve quality.

1. Which image bytes actually need to travel?

Calculate the byte budget first. This Python example uses decimal MB and GB and a proposed seven-day retention window. All examples use Python 3 and its standard library; save each block as a separate Python file and run it with Python 3. They are executable models of responsibilities that an Express application must implement, rather than a Node.js server or hosted-service integration.

photos_per_day = 10_000
original_bytes = 4_000_000
review_bytes = 400_000
retention_days = 7

for label, size in (("original", original_bytes),
                    ("review derivative", review_bytes)):
    daily_bytes = photos_per_day * size
    print(label)
    print(f"{daily_bytes / 1_000_000_000:.1f} GB per review pass")
    print(f"{daily_bytes * retention_days / 1_000_000_000:.1f} GB retained")
Enter fullscreen mode Exit fullscreen mode

With these assumptions, originals occupy 280 GB at steady state, before any additional copies your design retains. One derivative review pass transfers 4 GB rather than 40 GB. That arithmetic identifies a candidate change: stop fetching the original for every preview. It does not establish a monetary saving or an OCR quality score.

Build an acceptance set containing shipment identifiers, delivery dates, and handwritten exceptions from your own workflow. These are proposed evaluation fields, not a vendor response schema. Compare extracted text against labeled answers. If the derivative loses required characters, send the original to OCR; if it preserves them, measure the resulting bytes before adopting the transformation. Keep the reviewer able to request the original when a small image hides relevant detail.

Use private storage and short-lived presigned URLs for authorized access. Queue an internal image identifier, not an expiring URL or the image bytes. Generate access when the worker needs it. An expired URL and a deleted object are different states, so link expiry must never be treated as evidence of deletion.

2. How should an Express image review queue notify the uploader?

An Express request should finish after durable acceptance of the review work; it should not remain open while a person considers a photo. Coordinate image intake, an application record, and queue publication explicitly. An application outbox can preserve the intent to enqueue when the database and queue do not share a transaction.

Treat standard queues as at-least-once. A redelivery must not create another final decision.

The following local SQLite example exercises publication, rejection, and a repeated decision. It records the moderator and reason alongside one notification intent per photo. It uses one connection and an in-memory database to demonstrate the transaction boundary; production needs durable storage and concurrency controls appropriate to its database.

import json
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE reviews (
    image_id TEXT PRIMARY KEY,
    uploader_id TEXT NOT NULL,
    state TEXT NOT NULL,
    moderator TEXT,
    reason TEXT
);
CREATE TABLE notice_outbox (
    event_id TEXT PRIMARY KEY,
    payload TEXT NOT NULL
);
""")
with db:
    db.executemany(
        "INSERT INTO reviews VALUES (?, ?, 'pending', NULL, NULL)",
        [("delivery-label-a", "uploader-a"),
         ("delivery-label-b", "uploader-b")],
    )

def decide(image_id, outcome, moderator, reason):
    if outcome not in {"published", "rejected"}:
        raise ValueError("Expected published or rejected")
    if not moderator.strip() or not reason.strip():
        raise ValueError("Moderator and reason are required")
    with db:
        row = db.execute(
            "SELECT uploader_id, state, moderator, reason "
            "FROM reviews WHERE image_id = ?", (image_id,)
        ).fetchone()
        if row is None:
            raise KeyError(image_id)
        uploader, state, previous_moderator, previous_reason = row
        if state != "pending":
            if (state, previous_moderator, previous_reason) == (
                outcome, moderator, reason
            ):
                return
            raise ValueError("Conflicting final decision")
        db.execute(
            "UPDATE reviews SET state = ?, moderator = ?, reason = ? "
            "WHERE image_id = ?",
            (outcome, moderator, reason, image_id),
        )
        payload = {
            "image_id": image_id, "uploader_id": uploader,
            "decision": outcome, "moderator": moderator, "reason": reason,
        }
        db.execute(
            "INSERT INTO notice_outbox VALUES (?, ?)",
            (f"decision:{image_id}", json.dumps(payload)),
        )

decide("delivery-label-a", "published", "reviewer-a",
       "Delivery evidence accepted")
decide("delivery-label-b", "rejected", "reviewer-b",
       "Shipment label unreadable; upload a clearer photo")
decide("delivery-label-b", "rejected", "reviewer-b",
       "Shipment label unreadable; upload a clearer photo")
for event_id, payload in db.execute(
    "SELECT event_id, payload FROM notice_outbox ORDER BY event_id"
):
    print(event_id, payload)
assert db.execute("SELECT COUNT(*) FROM notice_outbox").fetchone()[0] == 2
Enter fullscreen mode Exit fullscreen mode

The publication state represents an application decision. It does not change the storage object's permissions. Published delivery evidence can remain private and require authorized access.

One final decision per image is a deliberate constraint in this example. Appeals need versioned decisions and corresponding event identifiers; silently replacing a final row would erase the explanation for an earlier notice. Preserve that distinction before adding another retry mechanism.

A notification worker must deliver outbox entries and record their disposition. Persisting an intent is not delivery. If a mail service accepts a message and the worker crashes before recording success, a retry may send another message; use the downstream service's documented idempotency facility where available, and retain the same event identifier. A unique database row alone cannot promise exactly-once email.

Both outcomes need a notice. Rejection should explain what the uploader can correct, while publication should confirm acceptance. Also provide a durable place to read the decision, since an email is a delivery attempt rather than the source of truth. Silence encourages duplicate uploads, which add storage and review work without adding evidence.

3. Choose where the work waits

Compare suppliers by their boundary, not by treating every backend product as interchangeable. The products below are real options for the image-processing portion of the workflow; none replaces the application's decision record or proves that a compressed label remains readable. Their documentation is a starting point for implementation review, not an OCR benchmark.

Option Useful fit Boundary and trade-off
Cloudinary Evaluate its image transformation workflow when producing review derivatives is the main integration task Image processing does not settle the application's review decision; test label readability and keep a separate decision record.
imgix Evaluate its rendering workflow when the application already has an image source A rendering layer is a different boundary from a moderation queue; retain responsibility for evidence lifecycle and uploader notices.
ImageKit Evaluate its image optimization workflow when delivery bandwidth is the main concern Optimization alone cannot establish OCR accuracy; compare required text against originals before accepting a smaller representation.

Infrai offers one key and one bill for image processing, queueing, email, and logs through a plain REST API, so an HTTP-capable worker doesn't need a service-specific SDK. Its single API key and unified billing reduce the service credentials to distribute and the separate invoices to reconcile across this review workflow. Coverage spans 295 routes in 20 modules. Its public, self-describing discovery surface also exposes request and response schemas without requiring a key, which helps inspect the adapter contract before connecting the worker. Those integration advantages do not establish better OCR quality, lower transfer volume, or atomic completion of the application workflow.

Before writing a hosted adapter, inspect the public discovery contract. This runnable, read-only check prints the returned JSON without guessing image-upload or queue fields. Set INFRAI_BASE_URL to the service's documented HTTPS base including its version segment; INFRAI_API_KEY supplies the bearer credential. Discovery is public and does not require that credential, but the example makes authenticated request handling explicit for the adapter boundary. It makes no upload, creates no review, and sends no email.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

base = os.environ["INFRAI_BASE_URL"].rstrip("/")
if not base.startswith("https://") or not base.endswith("/v1"):
    raise ValueError("Use the documented HTTPS base ending in /v1")
key = os.environ["INFRAI_API_KEY"]
request = Request(
    base + "/discovery", method="GET",
    headers={"Authorization": f"Bearer {key}", "Accept": "application/json"},
)
for attempt in range(5):
    try:
        with urlopen(request, timeout=30) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            print(json.dumps(json.load(response), indent=2))
        break
    except HTTPError as error:
        if error.code != 429 or attempt == 4:
            detail = error.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        delay = float(2 ** attempt)
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                deadline = parsedate_to_datetime(retry_after)
                delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds())
        error.close()
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

Use the returned request schema before implementing the write adapters, and preserve client idempotency identifiers on writes. This check verifies contract access only; it makes no claim about authenticated processing latency or OCR results.

Choose the boundary your team can verify. A logistics acceptance test should follow a private shipment photo through OCR, review, and each decision outcome, then check that a repeated task leaves the decision and notification intent unchanged. Don't treat a successful image transformation as evidence that this entire chain works.

4. When can the original photos be deleted?

The seven-day window above is a planning choice, not a legal retention recommendation. Pending review, an open appeal, or an unresolved notification should block routine deletion under this proposed policy; otherwise a cleanup worker could remove the only readable label before the uploader learns why it was rejected. Queue retention is a separate clock. For standard queues, keep retention within 30 days, use at-least-once consumer idempotency, and don't use a queue as the long-term decision ledger.

This executable policy example prints deletion candidates without deleting files. Its fields belong to the application, not a provider request schema. The decision rule is intentionally conservative: a final decision, a completed notification, no hold, and a closed evidence window must all agree before the original becomes eligible.

retention_days = 7
reviews = [
    {"id": "delivery-label-a", "age_days": 8, "state": "published",
     "notified": True, "hold": False},
    {"id": "delivery-label-b", "age_days": 8, "state": "rejected",
     "notified": True, "hold": True},
    {"id": "delivery-label-c", "age_days": 8, "state": "pending",
     "notified": False, "hold": False},
]
candidates = [
    row["id"] for row in reviews
    if row["age_days"] >= retention_days
    and row["state"] in {"published", "rejected"}
    and row["notified"] and not row["hold"]
]
assert candidates == ["delivery-label-a"]
print("Originals eligible for deletion:", candidates)
Enter fullscreen mode Exit fullscreen mode

Recheck those conditions at deletion time; a candidate list can become stale when a hold is added. Track deletion completion separately from link expiration, and apply the declared policy to additional retained copies as well. Notification delivery may remain unresolved, so this policy needs an explicit escalation path rather than allowing failed delivery to extend image retention indefinitely.

Keep the moderator, reason, outcome, and notification disposition under their own declared retention policy. Stop keeping expired original photos and redundant review derivatives after the required evidence window and holds close. The cost of that choice is concrete: if a disputed OCR character matters later, the decision record can explain who accepted it, but it cannot reconstruct pixels that were deleted. A longer evidence window buys that opportunity back at the cost of retaining more private image bytes.

Further reading

References for image-format decisions, supplier boundaries, and the local transaction example:

Top comments (0)