DEV Community

daxharrington5274
daxharrington5274

Posted on

Storage Object API: 3-Step Node.js Guide to Returned Malformed Responses in Resized Images

Short answer: validate the response body and object identity before publishing a resized image; use multipart transfer only for the large signed original when retrying the full file is too expensive.

Keep the receipt separate.

The useful answer is to stop treating a malformed response as an image-resizing problem. Treat it as a protocol-boundary failure. Keep the original signed proof-of-delivery document, generate the thumbnail as a separate byte stream, upload with an explicit length and content type, then validate the response before recording the object. This costs a few checks. It prevents a bad acknowledgement from becoming a retention record.

For a logistics system, that distinction matters. A signed delivery document may have a deletion deadline, while its small preview can be regenerated or deleted earlier. Large-file throughput is the first decision axis; response validation is the guardrail that keeps throughput from turning into silent corruption.

The failure is easy to miss: a resize worker can finish successfully, the upload can reach a gateway, and the application can still receive HTML, an empty body, or truncated JSON. If the database records the preview URL after only checking a 2xx status, the system has converted an uncertain network event into a durable claim. That claim then survives retries, cleanup jobs, and the document's retention clock. The fix belongs at the adapter boundary, before publication, not in a later dashboard.

I would trace one shipment through the system with a 180 MB signed scan and a 240 KB WebP preview. The scan can spend time in part retries while the preview finishes quickly. A response parser that reads both as if they were the same operation makes the trace misleading: the preview may be published while the original is still pending, or a gateway's HTML body may be stored as a JSON error and retried forever. Give each variant its own state, correlation id, checksum evidence, and retention deadline. Then an operator can answer the only useful question: which bytes were verified, and which bytes are still unknown?

Small and explicit wins.

Choice Throughput implication Operational trade-off
Single request for every object Fine for small thumbnails A retry can repeat a large body and hide partial work
Multipart upload for large originals Parts can be transferred and retried independently Completion state must be recorded and checked
Separate original and thumbnail objects The preview path stays small and disposable Metadata must link both objects without making the preview authoritative

My decision rule is plain: use a single request for a bounded thumbnail, and a multipart protocol for a signed original whose size can make a retry expensive. In both cases, parse the response as a protocol message, not as proof that the bytes are correct.

Why does a valid upload produce a malformed response?

The client usually has three different observations: the resize function returned bytes, the server accepted or rejected a request, and the response could be parsed. They are not interchangeable. A proxy can return an HTML error page where JSON was expected. A truncated connection can leave a status line but no usable body. A client can also assume JSON when the endpoint returns an empty success response.

That is why logging only response.ok is weak evidence. Log the status, content type, request correlation id, and a bounded body sample. Do not log signed document bytes. Check the declared content length when the transport exposes it, and compare the stored object's size and checksum through the storage interface before publishing a database row.

There is a nasty ordering trap here. If the application writes thumbnail_url before it has accepted the storage response, a malformed reply can create a durable reference to an object whose state is unknown. The repair is an outbox or pending-upload record: prepared, uploaded, verified, published. The deletion worker can understand those states instead of guessing from a URL.

What should the upload boundary actually verify?

The boundary needs fewer assumptions and more explicit invariants. The thumbnail bytes must be non-empty, below the configured preview limit, and labelled with the format produced by the resize step. The response must have an expected status class and a parseable representation, unless the protocol explicitly defines an empty body. The object key must be generated from document identity plus variant, never from an untrusted filename.

Here is a small TypeScript boundary. The endpoint is intentionally generic. It is an adapter seam, not a vendor setup recipe.

type UploadReply = {
  objectKey: string;
  etag?: string;
  checksumSha256?: string;
};

export async function uploadThumbnail(
  endpoint: string,
  key: string,
  bytes: Uint8Array,
): Promise<UploadReply> {
  if (bytes.byteLength === 0) throw new Error("empty thumbnail");
  if (bytes.byteLength > 2_000_000) throw new Error("thumbnail exceeds limit");

  const response = await fetch(endpoint, {
    method: "PUT",
    headers: {
      "content-type": "image/webp",
      "content-length": String(bytes.byteLength),
      "x-object-key": key,
    },
    body: bytes,
  });

  const contentType = response.headers.get("content-type") ?? "";
  const body = await response.text();
  if (!response.ok) {
    throw new Error(`upload failed: ${response.status}`);
  }
  if (!contentType.includes("application/json")) {
    throw new Error("upload acknowledgement is not JSON");
  }

  let reply: UploadReply;
  try {
    reply = JSON.parse(body) as UploadReply;
  } catch {
    throw new Error("upload acknowledgement is malformed");
  }
  if (reply.objectKey !== key) throw new Error("acknowledged key mismatch");
  return reply;
}
Enter fullscreen mode Exit fullscreen mode

The exact headers depend on the storage protocol. The invariant does not: the application should not publish an object until the acknowledgement describes the object it meant to write. A checksum returned by the service is useful evidence, but an opaque tag is not automatically a content hash; its meaning belongs to the protocol documentation.

How do large files change the recovery path?

For a signed original, split transfer changes the failure model. A failed part should be retried without rebuilding every earlier part. The client must retain the upload identifier, part numbers, byte ranges, and checksums until completion or explicit abort. Completion is a separate operation, so a successful part response is not a successful object.

This is where throughput benchmarks earn their keep. Measure end-to-end time for 10 MB, 100 MB, and 1 GB fixtures under a controlled concurrency limit. Record p50 and p95 upload time, retry bytes, verification time, and incomplete uploads left behind. A faster happy path that leaves abandoned multipart state is not faster in production; it has moved work to cleanup.

The thumbnail should not ride along as a special field inside the signed-document transaction. Store a relationship such as (shipment_id, document_id, variant, object_key, retention_deadline, state). The original follows the legal or operational deadline. The preview follows its own policy. When the deadline arrives, delete the original and its derivatives as one deliberate workflow, then verify the result.

Where is the runner-up approach better?

A single-request upload is the better choice for small, bounded thumbnails when latency and code size matter more than resumability. It is also easier to test with a local protocol stub. Multipart is the better choice when originals are large, networks are uneven, or retrying the full body would dominate the transfer budget. Neither choice fixes a malformed acknowledgement by itself.

The practical test matrix is short: valid JSON success, empty success body, HTML error body, truncated JSON, mismatched object key, checksum mismatch, timeout after request transmission, and a retry after an uncertain result. For the last case, use an idempotency key or deterministic object key, then verify before retrying. Otherwise the system can create duplicates while the operator believes it is repairing one upload.

A small amount of protocol discipline beats a large amount of post-incident archaeology. Keep the original immutable until its deadline, keep previews disposable, and make the state transition depend on verified evidence.

Sources

Top comments (0)