Node.js Multipart Storage for Large Generated PNG Image Upload Timeouts
A large generated image should go through multipart upload when retrying the whole request would make a timeout expensive, but multipart is only the transport choice. For a logistics SaaS that stores product images and b
A large generated image should go through multipart upload when retrying the whole request would make a timeout expensive, but multipart is only the transport choice. For a logistics SaaS that stores product images and builds tenant-scoped exports, the better design is a small upload state machine tied to a retention record. That makes retries bounded, completion explicit, and deletion auditable.
| Choice | Retry unit | Operational state | Best fit |
|---|---|---|---|
| Single request | Entire object | One pending request | Small objects that finish comfortably inside the request budget |
| Multipart session | One part | Upload ID, numbered parts, completion result | Large PNG or WebP files where a partial retry matters |
| Direct client upload | Depends on storage protocol | Client plus server coordination | Browser traffic that should not pass image bytes through the app server |
Recommendation: use multipart upload for the large-image path, persist its state per tenant, and treat successful completion as a separate event from part transfer. Keep a single-request path for small files. The split reduces wasted work without turning every upload into a multipart workflow.
This is a revenue-per-hour decision. I want the boring path to stay boring, because a one-person SaaS still has features to ship this week. The custom work belongs in tenant isolation, lifecycle state, and export correctness. Undifferentiated byte storage should remain behind a narrow interface. The trade-off is extra state in exchange for retrying less data.
How should Node.js handle a large generated PNG image upload timeout?
Start by naming the phase. A generic "upload timed out" error hides three different failures: the application stopped accepting bytes, an individual part did not finish, or all parts arrived but the multipart session was never completed. Retrying the original endpoint blindly can create another pending session while leaving the first one unresolved.
Do not guess.
The useful identifiers are the tenant ID, internal asset ID, upload ID, part number, attempt number, and final object key. Log those fields at phase boundaries. Do not log image bodies or temporary authorization material. A request duration alone cannot tell you whether the last acknowledged part exists or whether completion ran.
Short requests can still fail. A large PNG is especially good at exposing a request path that buffers the full body before storage begins. WebP may be smaller for some images, but the file extension must not decide trust or memory policy. OWASP recommends validating uploads with several controls, including an allowlist of extensions, type validation, generated filenames, size limits, authorization, and storage outside the webroot. Those checks belong before an asset becomes exportable.
My first debugging question would be concrete: did the process memory rise with bytes received? If yes, inspect buffering before tuning a timeout. A longer clock does not fix an application that retains the whole file in memory. If memory stays flat, correlate the final acknowledged part with the completion attempt. Then check whether the application persisted the receipt before the worker stopped, whether another worker tried to complete the same session, and whether the final object ever became eligible for export. This one trace crosses the request handler, worker, database, and object adapter, so it is far more useful than increasing every timeout and waiting for the next failure. The distinction can save an afternoon of changing unrelated proxy settings.
Retention must be data, not a bucket habit
A logistics tenant may replace a product photo, remove a product, or request an export while older images are approaching deletion. One timestamp is not enough to represent those cases safely. Store the asset state beside the upload state: uploading, ready, delete_pending, or deleted. Add a retention deadline and an immutable tenant owner. The export query should select only ready assets owned by that tenant.
The storage key should also be server-generated. A shape such as tenants/<tenantId>/assets/<assetId>/original is understandable, but the authorization decision must come from application data rather than trust in a client-supplied prefix. OWASP's upload guidance supports generated filenames and authorization checks for exactly this boundary.
Deletion deserves two steps. First, stop new exports from selecting the asset by moving it to delete_pending. Then delete the object and mark the record deleted after storage confirms the operation. If deletion fails, the record stays retryable and the image remains excluded from future exports. This favors correct tenant behavior over pretending that one network call is a transaction.
Four states are enough here.
Exports need their own retention rule. A generated archive is a derived object, not a second permanent copy of every image. Record which asset IDs and versions went into it, give the archive an expiry, and keep its key under the same tenant boundary. If an image becomes delete_pending before the export snapshot is created, exclude it. Once a snapshot exists, apply the declared export retention policy rather than silently changing its contents.
A small Node.js state machine
The application does not need to know a provider's SDK types. It needs an adapter with four operations and a repository that can compare state transitions. All code here is TypeScript, and the opaque tokens come from the storage adapter rather than being invented by the application.
type PartReceipt = { partNumber: number; token: string };
type ObjectStore = {
beginMultipart(input: { key: string; contentType: string }): Promise<{ uploadId: string }>;
uploadPart(input: {
key: string;
uploadId: string;
partNumber: number;
body: Uint8Array;
}): Promise<PartReceipt>;
completeMultipart(input: {
key: string;
uploadId: string;
parts: PartReceipt[];
}): Promise<void>;
abortMultipart(input: { key: string; uploadId: string }): Promise<void>;
};
Persist each returned receipt before scheduling the next part. On retry, load the known receipts and send only missing parts. Keep part numbers stable, sort receipts by partNumber for completion, and allow only one worker to move the asset from uploading to ready. The adapter owns protocol-specific signing and token handling; the service owns tenant policy.
type UploadRecord = {
tenantId: string;
assetId: string;
objectKey: string;
uploadId: string;
state: "uploading" | "ready" | "delete_pending" | "deleted";
parts: PartReceipt[];
retainUntil: string;
};
async function finishUpload(
store: ObjectStore,
repo: {
getForUpdate(tenantId: string, assetId: string): Promise<UploadRecord>;
markReady(tenantId: string, assetId: string): Promise<void>;
},
tenantId: string,
assetId: string,
): Promise<void> {
const upload = await repo.getForUpdate(tenantId, assetId);
if (upload.state === "ready") return;
if (upload.state !== "uploading") throw new Error("upload cannot be completed");
const parts = [...upload.parts].sort((a, b) => a.partNumber - b.partNumber);
if (parts.length === 0) throw new Error("upload has no confirmed parts");
await store.completeMultipart({
key: upload.objectKey,
uploadId: upload.uploadId,
parts,
});
await repo.markReady(tenantId, assetId);
}
There is an awkward boundary in that example: storage completion can succeed just before the database update fails. Do not hide it. A recovery job should revisit uploading records, reconcile them through the adapter, and move only confirmed objects to ready. The exact reconciliation call depends on the selected object-store protocol, so it belongs in the adapter.
Use bounded attempts. After the retry budget is exhausted or retention policy says the pending upload is stale, abort the multipart session and mark the record for cleanup. Infinite retries turn temporary failures into permanent operational load.
Multipart has a real limitation: it creates session, receipt, completion, reconciliation, and cleanup work. It is not suitable for every image. If ordinary uploads already finish inside the end-to-end request boundary, choose the single-request path; its smaller state surface is worth more than theoretical retry efficiency. If browser-to-storage transfer is required to protect app-server bandwidth, choose direct client upload and accept the additional authorization and validation boundary. Those are architectural alternatives, not fallback marketing claims.
Test the failure boundaries before raising timeouts
A useful test suite interrupts each phase separately. Cut the connection during one part and confirm that acknowledged parts are not uploaded again. Fail completion and confirm that the asset never appears in an export. Let completion succeed while the database write fails, then verify that reconciliation reaches ready once and does not duplicate the asset record.
Use two tenant fixtures.
Also test the ownership checks with two tenant IDs. Tenant B must not resume, complete, export, or delete Tenant A's upload even if it learns an asset ID or upload ID. Upload validation should reject a mismatched type and an oversized object before the record can become ready. These tests cover the security boundary described by OWASP rather than relying on an extension such as .png or .webp.
For deployment, add the multipart path behind a size threshold and keep the existing small-object route. Watch counts by state, part retry counts, completion latency, stale sessions, deletion retries, and export exclusions. Avoid dimensions that contain raw object keys or user filenames; tenant and asset identifiers can also create excessive metric cardinality, so keep high-detail correlation in logs.
Then run one synthetic upload through the same production path on a schedule. It should create an asset, complete it, verify it is eligible for export, move it to delete_pending, and delete it. That checks the lifecycle rather than a health endpoint that never transfers bytes.
When the simpler paths win
Single-request upload is the runner-up for images that reliably fit within the smallest request-body and duration limits across the whole path. It has less state, fewer cleanup duties, and a smaller test matrix. Keep it. Multipart everywhere would spend engineering time on receipts and recovery where a normal request already works.
Direct client upload is stronger when app-server bandwidth is the bottleneck and the client can manage retries. It also widens the authorization surface. The server still has to issue narrowly scoped permission, bind the object to a tenant-owned asset, validate the completed upload, and prevent an unverified object from entering an export. Moving bytes away from Node.js does not move policy away from the application.
A managed S3-compatible service can supply the object API while the application retains this state model. DigitalOcean Spaces documents S3 compatibility, which can reduce adapter work, but compatibility does not remove the need to test the exact operations and failure behavior the application uses. A self-hosted implementation may offer more control and more operations work. Neither choice changes the core decision: retention, ownership, completion, and deletion remain application concerns.
The practical stopping rule is plain. Use the least complicated transfer path that survives your measured object sizes and request boundaries. Introduce multipart only where partial retry earns back its state cost. Keep exports tenant-scoped, and make deletion observable. That is enough machinery to fix the timeout without building a storage platform as a side project.
Sources
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.