DEV Community

YvesSterling6854
YvesSterling6854

Posted on

Healthtech Report PNGs: US/EU Object Storage and Signed Download Links

When a healthtech app serves an AI-generated report image to an authenticated customer, large-file throughput changes the design. The useful pattern is to keep the PNG write on the server, store it in a private regional bucket, and return a short-lived signed download link. The API route should return metadata, not a base64 image stuffed into JSON.

Short answer: use a Next.js API route as the authorization boundary, stream or pass the generated PNG to object storage, then sign a GET for the customer. Record the object key and region beside the report record so an evaluator can find the exact artifact later.

That choice is about bytes and control. It keeps storage credentials away from the browser, avoids a second full copy inside a JSON response, and lets the download path use HTTP cache policy deliberately. The first prototype can be a notebook that saves one file.

Production needs a measurable handoff between generation, storage, and delivery.

What should a Next.js API route measure for US/EU report PNG storage?

Start with the failure you can actually diagnose. For every report, persist a generation id, tenant id, approved region, object key, content type, byte count, upload duration, signing duration, and download outcome. A successful model call is not a successful customer workflow if the report is too slow to retrieve or the wrong regional bucket receives it.

The region is an application decision, not something to infer from a browser request. Resolve the tenant's allowed location before generation finishes, choose the matching private bucket, and reject a request whose policy does not identify one. Keep the region in the record. It becomes essential when an evaluation harness compares throughput across US and EU workloads.

The simple approach that failed my design review was returning base64 from the route and letting the client upload it. The JSON envelope made the response larger, the browser became responsible for another authenticated transfer, and the stored object was no longer joined naturally to the report's evaluation record. Small demos tolerate that ambiguity. Large images don't.

The experiment: server-side bytes versus browser-side upload

For the experiment, hold image generation constant and compare two paths: server-side upload from the route, and a browser upload after the route returns encoded bytes. Measure p50 and p95 time to a usable signed link, total bytes transferred by the API, upload retries, and customer download completion. Run the same matrix for a small report and a representative large PNG, with one slow client and one concurrent burst. Record the time at four boundaries: generation complete, first upload byte, object write complete, and signed link opened. Those timestamps tell you whether the bottleneck is the worker, the storage connection, or the customer's network; a single end-to-end duration cannot. Do not use storage latency as a proxy for image quality.

The server-side path has fewer moving parts for a private report: authenticate once, attach the object key to the report row, write the bytes, and sign a read. Its cost is that the route or a worker carries the upload bandwidth. For large files, that is a real capacity question, so a queue and bounded concurrency may be better than making every request wait synchronously.

The browser path can reduce server bandwidth, but it requires a carefully scoped upload authorization and a matching CORS policy. It also needs an explicit state machine for abandoned uploads, expired permissions, and a report that was generated but never stored. Your mileage may vary; the right choice depends on file size, concurrency, and the enforcement required by the tenant policy.

This is the point where notebook-to-prod work often gets too optimistic. A 300 KB fixture says nothing about a multi-megabyte PNG under ten simultaneous report requests. Test representative payloads, slow clients, a retried request, and a route process that is restarted after generation but before the storage record is committed.

A focused Python storage boundary

The route itself can be JavaScript in a Next.js application, but the storage boundary below is Python because the worker is easier to evaluate independently. ObjectStore is an application interface; its implementation should use the selected provider's documented SDK or HTTP contract. The example keeps the important invariants visible without inventing a vendor-specific endpoint.

from dataclasses import dataclass
from typing import Protocol
from uuid import uuid4


class ObjectStore(Protocol):
    def put(self, *, key: str, body: bytes, content_type: str) -> None:
        ...

    def sign_get(self, *, key: str, expires_seconds: int) -> str:
        ...


@dataclass(frozen=True)
class StoredReport:
    key: str
    region: str
    download_url: str


def store_report_png(
    store: ObjectStore,
    *,
    tenant_id: str,
    region: str,
    png_bytes: bytes,
    expires_seconds: int = 600,
) -> StoredReport:
    if not png_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
        raise ValueError("expected a PNG payload")
    if not tenant_id or not region:
        raise ValueError("tenant and region are required")

    key = f"reports/{tenant_id}/{uuid4().hex}.png"
    store.put(key=key, body=png_bytes, content_type="image/png")
    url = store.sign_get(key=key, expires_seconds=expires_seconds)
    return StoredReport(key=key, region=region, download_url=url)
Enter fullscreen mode Exit fullscreen mode

The fresh key makes a retry an additional object instead of an accidental overwrite. That is a deliberate trade-off: cleanup and idempotency now belong in the application workflow. A production implementation should attach a request id to its database record and reconcile an object written before a worker restart. It should also cap accepted size before buffering bytes, or use a streaming implementation when the payload and concurrency make buffering unsafe.

The signed URL is a bearer credential. Treat it like one: keep it out of ordinary logs, choose an expiration that matches the customer action, and never put the bucket credential in client code. For browser caching, define Cache-Control based on the confidentiality and lifetime of the artifact; MDN documents the response directives and their interaction with shared caches. A private report should not accidentally become a shared-cache object because a proxy reused a permissive header.

Where this design is not suitable

The catch is that private object storage with expiring links is a poor fit for permanent public assets, image transformation pipelines, or retention policies that require immutable versions and legal holds. Choose a public delivery system, an image service, or a storage platform with those controls when those requirements are primary.

It is also a poor fit when every upload must complete inside a short synchronous request and the generated files are large. Move the write to a worker and return a report status, or use a provider-supported multipart or direct-upload flow with a narrowly scoped authorization. Do not hide that queue behind a fake success response; the customer needs to know whether the report is ready.

The decision table is intentionally small:

Constraint Prefer the server-side signed-link pattern Reconsider it when
Privacy The object must stay private and access can expire The asset is meant for public, permanent delivery
Throughput A worker can absorb bounded upload concurrency A synchronous request must carry very large files
Residency The tenant maps to an approved regional bucket The system needs automatic cross-region placement
Evaluation The key and generation id live with the report The artifact does not need audit or replay

The decision rule I would ship

For authenticated healthtech reports, keep the PNG private, select its region before writing, use a server-side or worker-owned upload, and return a signed GET link only after the object and report metadata are joined. Then measure p95 time to a usable link, bytes moved through the API, abandoned uploads, and download completion by region.

The answer is not “always use a signed URL.” It is “make the access lifetime, region, and byte path explicit, then test them with realistic files.” That gives a prompt-cost-aware AI team an evaluation record it can inspect instead of a hopeful screenshot from a notebook.

Sources

Top comments (0)