Short answer: for a US/EU SaaS that stores AI-generated PNG training artifacts, let the Next.js API route authorize an upload and record its lifecycle, but send the image bytes directly to regional object storage; issue a short-lived signed download link only after the object has been finalized and matched to an immutable retention record.
That division keeps the application route out of the large-file data path. It also makes the two decisions that matter later -- who may read the artifact, and when it may be deleted -- explicit database state instead of implications buried in an object name. The least complex credible design has three operations: initiate an upload, finalize its evidence, and authorize a download. One identifier follows all three.
This is an exactly-once accounting problem even though the network remains at-least-once. Treat retries as normal.
What slows AI-generated PNG storage in a US/EU SaaS?
A Next.js API route should control the transaction, not carry the payload. On initiation, it authenticates the tenant, resolves the tenant's approved US or EU placement, reserves an artifact ID, fixes the retention class, and asks the storage signer for a constrained upload capability. The browser or generation worker then uploads the PNG without relaying tens or hundreds of megabytes through the web runtime. On completion, the route verifies the expected object identity and records durable evidence such as byte length, media type, checksum, generation job ID, and retention deadline.
The artifact should not become downloadable merely because an object exists. Object creation and business acceptance are separate events, and retries can expose the gap between them. Keep a small state machine: reserved, uploaded, available, then expired or deleted. Only available can produce a signed download link. A repeated completion call with the same idempotency key returns the already committed result; the same key with a different checksum is a conflict that deserves investigation, not an overwrite.
This distinction is easy to miss. A generation worker can time out after a successful upload and submit completion again, while a user can double-click an action or a queue can redeliver it. If every retry creates a new object, retention counts, audit history, and storage reconciliation all drift. If every retry overwrites a stable key, an earlier signed link may suddenly identify different bytes. An immutable object identity plus an idempotent metadata commit avoids both outcomes, and it gives support staff one artifact ID with which to trace authorization, upload, finalization, link issuance, and erasure.
Don't derive region from a request header supplied by the browser. Resolve it from tenant policy on the server, persist that decision with the artifact, and reject any later operation whose region disagrees with the record. “US” and “EU” are routing labels here, not claims of legal compliance; contractual scope, subprocessors, replication, backups, and deletion obligations still need review outside this code path.
The byte path has two clocks
The control plane is deliberately small: identity, authorization, idempotency, placement, retention, and audit. The data plane is the byte transfer between producer or consumer and object storage. Mixing them by accepting a large multipart body in a Next.js function looks convenient, but it couples throughput to application memory, request duration, concurrency, and deployment limits. It also turns an otherwise cheap retry into another full transfer through the application tier.
Use an opaque object key. Human-readable course titles, learner identifiers, and prompts do not belong in it; they change, leak context into logs, and complicate erasure review. A key assembled from tenant ID, fixed region, artifact ID, and version is enough. Keep searchable business metadata in the database, where authorization and audit queries can be applied consistently.
The following Go types show the contract that a Next.js route can call through an internal service. The interface is intentionally storage-neutral: signing remains behind the adapter, while retention and idempotency remain owned by the application.
package artifacts import ( "context" "errors" "time" ) type State string const ( Reserved State = "reserved" Available State = "available" ) type Artifact struct { ID string TenantID string Region string ObjectKey string State State SHA256 string Bytes int64 RetainUntil time.Time IdempotencyKey string } type Repository interface { Reserve(ctx context.Context, artifact Artifact) (Artifact, error) Finalize(ctx context.Context, id, idempotencyKey, sha256 string, bytes int64) (Artifact, error) FindAuthorized(ctx context.Context, tenantID, artifactID string) (Artifact, error) } type Signer interface { SignPNGUpload(ctx context.Context, region, objectKey string, expiresAt time.Time) (string, error) SignPNGDownload(ctx context.Context, region, objectKey string, expiresAt time.Time) (string, error) } var ErrNotAvailable = errors.New("artifact is not available") There is no storage credential in the browser and no provider-specific type in the ledger. The signed capability is narrow and temporary, while the durable record contains the decision inputs. That separation matters during migration: replacing a signer adapter should not rewrite the artifact state machine or the audit schema.
Duplicate completion is a data-integrity test
An upload URL is permission to attempt a write, not proof that the accepted artifact exists. The completion operation closes that gap. It should compare the submitted object identity with the reservation, confirm the finalized metadata through the storage adapter, validate the permitted PNG media contract, and commit available with one audit event in the same application transaction. If checksum validation is too expensive to repeat at read time, do it once before availability and retain the result as evidence.
Be precise about “exactly once.” No HTTP API can make a client transmit only once, and a signer cannot prevent every retry. The enforceable property is that one logical completion key produces one state transition and one audit event. Store the idempotency key under a uniqueness constraint scoped to the tenant and operation; store a request fingerprint beside it. An identical replay reads the original result. A mismatched replay fails closed.
package artifacts import ( "context" "fmt" "time" ) type Service struct { repo Repository signer Signer now func() time.Time } type Download struct { ArtifactID string URL string ExpiresAt time.Time } func (s Service) IssueDownload( ctx context.Context, tenantID string, artifactID string, lifetime time.Duration, ) (Download, error) { artifact, err := s.repo.FindAuthorized(ctx, tenantID, artifactID) if err != nil { return Download{}, err } if artifact.State != Available { return Download{}, ErrNotAvailable } if !s.now().Before(artifact.RetainUntil) { return Download{}, fmt.Errorf("retention period ended") } expiresAt := s.now().Add(lifetime) if expiresAt.After(artifact.RetainUntil) { expiresAt = artifact.RetainUntil } url, err := s.signer.SignPNGDownload(ctx, artifact.Region, artifact.ObjectKey, expiresAt) if err != nil { return Download{}, err } return Download{ArtifactID: artifact.ID, URL: url, ExpiresAt: expiresAt}, nil } The route returning this value should authenticate before calling the service, record the actor and artifact ID in an append-only audit event, and set Cache-Control: private, no-store on the API response that contains the bearer link. MDN defines private as allowing storage only in a private cache and no-store as instructing caches not to store the response. The signed link's own response policy is a separate decision: training images meant for repeated viewing may benefit from controlled private caching, while especially sensitive artifacts may not. I'm not sure there is one correct cache lifetime across course previews, grading evidence, and regulated training records; access patterns and the governing retention policy settle it.
Keep URLs out of ordinary application logs. Log the artifact ID, principal, policy decision, expiration timestamp, and outcome instead. A signed URL is transient authorization material -- preserving it in an analytics stream defeats much of the point of making it short-lived.
Measure throughput at the object boundary
Three common shapes solve different problems. The comparison belongs after the invariants because a fast transfer path cannot repair ambiguous ownership or deletion policy.
| Shape | Large-file throughput | Operational benefit | The catch |
|---|---|---|---|
| Application-proxied upload | Application handles every byte | One familiar authentication boundary | Not suitable when file size or concurrency approaches runtime limits; keep it for small payloads that require inline transformation |
| Direct signed upload | Storage handles the byte stream | Application controls intent without proxying payloads | Requires a finalize step, abandoned-upload cleanup, and strict capability scope |
| Asynchronous ingestion | Worker fetches or receives generation output | Natural backpressure and retry control | Adds queue state and delays interactive availability; use it when generation already runs off-request |
For this edtech workload, direct signed upload is usually the cleanest starting point when learners or generation workers need interactive completion and PNGs are large. Asynchronous ingestion becomes preferable when generation jobs already have durable queue semantics or when scanning and validation must finish before anything is visible. Application proxying is defensible for small, bounded files or mandatory streaming transforms, but it is the wrong default for high-throughput artifacts because scaling web instances then scales an avoidable copy operation.
Measure the boundaries rather than trusting a synthetic headline. Track reserved-to-available latency, bytes transferred by region, abandoned reservations, checksum mismatches, duplicate completion replays, download authorizations, and deletion lag after retain_until. Reconciliation should independently compare available database records with objects and report both orphans and missing objects. It must be read-only before it is allowed to repair anything.
Cost belongs in that measurement, but it is not the architecture. Storage volume, request count, egress path, retrieval class, replication policy, and incomplete uploads can all matter; the relevant mix depends on the workload and should be tested against the current terms of any candidate service. Google Cloud Storage's documentation is one public example of the breadth of operational topics a storage evaluation must cover, including uploads, downloads, object lifecycle management, locations, and access control. Use the same checklist for every adapter rather than allowing one provider's vocabulary to define the design.
A failure-injection rollout for training artifacts
Start with shadow records: reserve artifact IDs and compute placement and retention decisions while the existing path remains authoritative. Compare object counts, byte totals, checksums, and regional placement daily. Then enable direct upload for one internal tenant, make completion idempotent, and test interrupted transfers plus repeated completion requests before expanding traffic.
Deletion needs more caution than upload. First emit an expiration candidate and require reconciliation to confirm that the database deadline, legal hold state, and object identity agree. Next run deletion in a narrow cohort with an immutable audit event for the decision and outcome. Only then automate the broader schedule. The rollback is to stop issuing new reservations and pause deletion; already available artifacts remain readable until their recorded policy says otherwise.
The limitation is explicit: this pattern is not suitable when every byte must be inspected or transformed synchronously inside the application boundary. Keep an application proxy for that bounded case, or choose asynchronous ingestion when inspection can happen before publication. Direct transfer optimizes throughput; it does not remove the need for malware review, content policy, accessibility processing, backup analysis, or jurisdiction-specific legal assessment.
One rule survives every adapter choice: a download link is temporary authority, while the artifact record is the durable truth.
References
Further reading
The two references above are the primary starting points for HTTP cache behavior and for the object-storage operational surface discussed here.

