TL;DR — For an edtech report, the important choice is not where the bytes live. It is who can explain their lifetime. Keep report authorization and retention in the application, accept the image as multipart/form-data, and record an explicit upload state before the report points at the object. Use an application relay when auditability matters most; use a direct or resumable path when the byte stream is the bottleneck. In every case, make deletion a recorded transition rather than a hopeful bucket operation.
Here is the diagram in words: authenticated report request → image validation → object write → retention record → report reference → authorized read → deletion transition. The object store holds bytes. The report service owns the relationship.
| Path | Pick this when | The trade-off to document |
|---|---|---|
| Application relay | A report API must make one visible authorization decision and generated images are moderate in size | The application carries the request body and needs an upload limit |
| Direct multipart upload | The client can receive a short-lived, scoped permission and application bandwidth is the constraint | Completion, abandoned parts, and ownership records need separate handling |
| Resumable upload | A retry of the whole image is painful on an unreliable connection | The state machine grows, so integration tests and cleanup become part of the feature |
| Worker-to-service upload | A trusted image generator already runs beside the report workflow | The service still has to authorize the report ID and record the result |
The table is a reliability decision table, not a provider comparison. A generated image can be disposable while its report remains available. It can also need to disappear with the report. Put that rule in a retention record; do not leave it implicit in an object prefix.
1. Which path makes the report lifecycle easiest to explain?
Start with the failure a support engineer will need to answer. “The upload returned 201” is a weak answer. It says one request completed. It does not say that the report can read the image, that its retention deadline was saved, or that deletion will find the same object later.
Choose the application relay when one authorization boundary is more valuable than moving bytes away from the API. The handler can authenticate the customer, authorize the report, validate the form field, write the object, and persist its ownership record in one visible workflow. This is usually the easiest path to test.
Choose direct multipart upload when the application should not carry the image body. The application must issue a narrowly scoped permission and receive a completion event it can reconcile with a report. A permission to write bytes is not permission to read a report. Keep those decisions separate.
Choose resumable upload when a failed transfer would otherwise force a customer or worker to resend the complete image. It earns better retry behavior by adding unfinished-upload state. Give that state an age limit. An abandoned transfer must not survive forever simply because it never reached the “available” transition.
Choose the worker path when image generation already happens in a trusted service. The worker may know the image, but the report service should still validate the report relationship. Passing a customer-supplied filename or report identifier through without a server-side check makes the worker an authorization boundary by accident.
For this scenario, the application relay is the clearest reference implementation. It keeps the hard policy decisions close to the report domain, where deletion can be tested with the same records that decide access.
2. How should Node.js upload AI-generated images to object storage?
The multipart body is a transport detail. The lifecycle is the design. The handler below accepts a File from a standard FormData request and writes it through a deliberately small object-store interface. The adapter can target a self-hosted service or a compatible object API without moving authorization into that adapter.
The example uses a 10 MiB request limit and a 30-day retention value to make the boundary concrete. Those are policy examples, not universal defaults. In a real service, configure them from the report domain and test the boundary values: empty input, exactly the limit, one byte over, and an already expired record.
type UploadState = "pending" | "available" | "deleting" | "deleted";
type ImageRecord = {
reportId: string;
objectKey: string;
contentType: string;
byteLength: number;
state: UploadState;
createdAt: string;
deleteAfter: string;
};
type ObjectStore = {
put(input: {
key: string;
body: ReadableStream<Uint8Array>;
contentType: string;
contentLength: number;
}): Promise<void>;
};
const allowedTypes = new Set(["image/png", "image/jpeg", "image/webp"]);
const maxBytes = 10 * 1024 * 1024;
export async function uploadReportImage(
request: Request,
reportId: string,
store: ObjectStore,
saveRecord: (record: ImageRecord) => Promise<void>,
canEditReport: (request: Request, reportId: string) => Promise<boolean>,
): Promise<Response> {
if (!(await canEditReport(request, reportId))) {
return new Response("Not found", { status: 404 });
}
const form = await request.formData();
const value = form.get("image");
if (!(value instanceof File) || !allowedTypes.has(value.type)) {
return new Response("Unsupported image", { status: 415 });
}
if (value.size === 0 || value.size > maxBytes) {
return new Response("Image size is not allowed", { status: 413 });
}
const now = new Date();
const record: ImageRecord = {
reportId,
objectKey: `reports/${crypto.randomUUID()}`,
contentType: value.type,
byteLength: value.size,
state: "pending",
createdAt: now.toISOString(),
deleteAfter: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString(),
};
await store.put({
key: record.objectKey,
body: value.stream(),
contentType: record.contentType,
contentLength: record.byteLength,
});
await saveRecord({ ...record, state: "available" });
return Response.json({ objectKey: record.objectKey }, { status: 201 });
}
There are two details worth keeping. First, generate the key on the server. A customer's filename can contain personal data, collide with another upload, or carry path-like characters. Keep that name only as display metadata if the product needs it. Second, do not manually set the multipart Content-Type header in the client. The runtime adds the boundary parameter that lets the receiver parse the body.
The persistence order deserves a deliberate decision. The compact example writes the object and then saves the available record. Production code needs a reconciliation path for a successful object write followed by a record failure. Another valid design saves pending first, then writes the object, then advances the state. The choice is less important than making the orphan detectable by an upload identifier, creation time, and state. A bucket listing is not a lifecycle database.
The response code is only one checkpoint.
Picture a worker that receives HTTP 201, loses its connection before saving the result, and retries with the same idempotency key six seconds later. The service should find the first record, compare its report relationship, and return the existing outcome. If the first object write succeeded but the record did not, reconciliation needs enough metadata to identify that orphan without scanning unrelated customer data. That means a server-created upload ID, an explicit state, a creation timestamp, and a bounded cleanup rule. It also means a metric for records that have stayed pending too long. This is more bookkeeping than the happy path, but it is the part that turns a timeout from a mystery into a recoverable transition.
Small state. Clear evidence.
3. How should a generator retry without creating mystery images?
A worker should send a stable idempotency key for one logical image. The service stores that key with the pending record and returns the existing outcome if the worker repeats it. That makes a timeout recoverable without guessing whether the first request reached the object store.
export async function sendGeneratedImage(
endpoint: string,
reportId: string,
image: Uint8Array,
token: string,
idempotencyKey: string,
): Promise<void> {
const form = new FormData();
form.set("image", new Blob([image], { type: "image/png" }), "generated.png");
const response = await fetch(
`${endpoint}/reports/${encodeURIComponent(reportId)}/images`,
{
method: "POST",
body: form,
headers: {
authorization: `Bearer ${token}`,
"idempotency-key": idempotencyKey,
},
},
);
if (response.status === 429) {
throw new Error("Retry with bounded exponential backoff and jitter");
}
if (!response.ok) {
throw new Error(`Image upload failed with status ${response.status}`);
}
}
The worker should not retry every failure the same way. A rejected type or an unauthorized report is a terminal result. A timeout during the byte transfer is an investigation through the idempotency record. A rate limit is a bounded retry with jitter. The distinction belongs in metrics as well as control flow.
The most useful log fields are an internal request ID, report ID, idempotency key hash, byte count, state transition, duration, and outcome. Do not log image bytes, bearer tokens, or raw object keys when a key could reveal an identifier. A short, stable identifier is enough to connect the upload request, object write, report reference, and deletion job.
4. How do you prove retention and deletion worked?
Treat retention as a state machine with a small vocabulary: pending, available, deleting, and deleted. The report can reference only available. A deletion job selects records whose deleteAfter has passed, changes one to deleting, attempts the object deletion, and records deleted only after the operation succeeds. Retrying a delete should be harmless.
That ordering gives observability a shape. Count transitions. Count records past deleteAfter. Measure the age of the oldest pending upload. Alert on a stalled job or a growing backlog, not on a customer-facing image URL. An empty object listing does not prove that all retention records were handled; it proves only that the listing was empty at that moment.
Read access follows the same ownership rule. Authorize the customer against the report on every read, then return a short-lived scoped download response or stream the bytes through the service. CORS controls which browser origins may make cross-origin requests. It does not authenticate the customer or prove that an image belongs to the requested report.
Test the transitions rather than only the happy response. Use a misleading filename with a valid image, an oversized body with a truthful content type, a repeated idempotency key, a timeout after the object write, an expiration during a pending upload, and a deletion retry. Each test should leave a state that a reconciliation job can explain.
5. Limits worth accepting before choosing a path
The relay is straightforward to audit, but it consumes application bandwidth. Direct upload moves that byte path elsewhere, but it adds permission expiry and completion bookkeeping. Resumable upload improves recovery for interrupted transfers, while adding unfinished state and more integration cases. A worker path simplifies the client, but it does not remove report authorization.
None of these paths decides the retention policy for you. For generated images attached to authenticated edtech reports, keep the rule plain: the report service owns access, the object store owns bytes, and the retention record owns the deadline. Multipart is the wire format. It is not the authorization model.
Top comments (0)