Receipt Pipelines: Browser Uploads, Proxy Streams, and Signed URLs for Private Storage

2026-12-02来源 dev.toEnglish

Short answer: for a receipt service that must keep the original file, use a short-lived signed upload for ordinary large files, with a small server-mediated path for exceptional validation and recovery. A browser-to-object-store transfer keeps application servers out of the byte stream, but privacy comes from authorization, key design, and lifecycle rules—not from CORS alone.

The operational constraint is throughput. Receipt images and PDFs arrive in bursts, and a 200 MB scan should not occupy a Node.js process while an OCR worker is waiting for the same tenant. I first sketched a POST /upload endpoint that accepted multipart data, checked a session, and streamed to storage. It was easy to explain and expensive to run: every byte crossed the app tier, retries competed with API traffic, and a client disconnect left several states to reconcile.

The better shape is a two-phase intake. The app authorizes an object key and returns a signed upload request. The browser sends bytes to storage. The app then records completion and queues receipt processing. Keep the original immutable; derive thumbnails, OCR text, and normalized metadata as separate objects. That split also gives support staff a useful answer to “where is my receipt?” because the ledger can distinguish a grant that was never used, an object that arrived without a callback, and a file that is waiting for OCR.

That distinction saves hours.

Measure before copying this design: p95 upload duration by size band, app-tier egress, retry count, time from upload completion to OCR, and abandoned objects after 24 hours. Your mileage may vary when users are on mobile networks or when storage is in a distant region.

Rollout plan for receipt intake without rewriting the ledger

The upload row is the source of truth for workflow state, while object storage is the source of truth for bytes. Create the row before issuing a grant, and never let a path supplied by the browser choose another tenant's prefix. This ordering makes cleanup and customer-visible status deterministic even when tabs are closed mid-transfer.

How should browser uploads handle signed URLs and private storage?

Treat a signed URL as a capability with a narrow scope, not as a login token. The API should authenticate the tenant, choose a non-guessable key, bind an expected content length and media type, and set a short expiry. The response can contain a URL plus method and headers; the browser never receives a bucket-wide credential.

The object key should carry an internal tenant identifier and upload id, for example tenant/8f2c/upload/91b7/original.pdf. Do not put an email address, invoice number, or other business identifier in a public URL. Store those attributes in your database, where access checks are easier to audit.

CORS is a browser permission boundary. It controls which origins may read a response or issue a cross-origin request, but it does not make an object private and it does not replace signature verification. Allow only the production origins you operate, list the exact methods and headers used by the upload, and avoid a wildcard origin when credentials or sensitive responses are involved. A storage policy must still deny anonymous reads and writes.

Here is the shape of a provider-neutral Node.js handler. The signing library is deliberately abstract; its contract is what matters.

type UploadGrant = { url: string; method: "PUT"; headers: Record<string, string>; expiresAt: string; key: string; }; async function createReceiptGrant(input: { tenantId: string; bytes: number; contentType: string; }): Promise<UploadGrant> { if (!/^application\/(pdf|octet-stream)$/.test(input.contentType) && !input.contentType.startsWith("image/")) { throw new Error("unsupported media type"); } if (input.bytes <= 0 || input.bytes > 500 * 1024 * 1024) { throw new Error("file size outside policy"); } const uploadId = crypto.randomUUID(); const key = `tenant/${input.tenantId}/upload/${uploadId}/original`; const signed = await signer.put({ key, contentType: input.contentType, contentLength: input.bytes, expiresInSeconds: 300, }); await uploads.insert({ uploadId, tenantId: input.tenantId, key, expectedBytes: input.bytes, state: "pending", }); return { ...signed, key, expiresAt: new Date(Date.now() + 300_000).toISOString() }; } 

The completion endpoint should verify object metadata (size, checksum where available, and key ownership) before enqueueing OCR. A client-supplied complete=true is only a hint. If the browser drops offline, a later status check can discover the pending object without replaying the entire upload.

Benchmarking proxy streams: which throughput tests matter?

Proxying is the right tool when the server must inspect bytes before storage, when a customer requires a single audited ingress point, or when the client cannot perform signed requests. It also gives you one place to normalize multipart quirks from older integrations. The cost is direct: application connections, memory or disk buffering, outbound bandwidth, and a larger blast radius during a traffic spike.

Avoid buffering a full receipt in RAM. In Node.js, stream from the request to a bounded temporary file or directly to a storage multipart writer, enforce a byte limit while reading, and abort downstream work when the client cancels. A proxy should return an upload id and make processing asynchronous; keeping an HTTP request open until OCR completes turns a slow dependency into a capacity leak.

The failure modes differ. A direct upload can leave an object with no database row if the completion callback never arrives. A proxy can leave a database row whose stream stopped halfway through. Both need an explicit state machine such as pending, uploaded, processing, complete, and rejected, plus a sweeper that marks stale pending records and deletes unclaimed objects after a retention window.

That state machine is where the boring details become product behavior. Suppose a user selects three receipts, the first part of the second file times out, and the browser retries after the tab regains focus. The API should return the same upload id for an idempotency key, while the storage layer accepts only the missing parts; a second completion request should be harmless, and an OCR worker should see one logical receipt rather than two jobs. Record attempt counts, byte totals, and timestamps with the upload id. When support investigates a missing document, those fields let them tell apart an expired grant, a client cancellation, a policy rejection, and a worker delay without asking the customer to upload private paperwork again. This is also why I avoid deriving state from object listing alone: listings can lag application intent, and a similarly named object says nothing about which tenant was authorized to create it.

Retry and failure handling for completion events

Single-request PUT is fine for small scans, but a flaky connection makes a 200 MB retry painful. Multipart upload lets the client retry a failed part, yet it adds an abort protocol and a limit on unfinished sessions. Pick a part size from measured latency and memory, then cap concurrent parts per browser and per tenant. The exact numbers belong in a load test, not in a blog promise.

Receipt processing should be decoupled from upload completion. Emit one durable event containing the upload id and object key; workers fetch the original, write derived artifacts, and record a content hash. Make the consumer idempotent so a duplicate event cannot create duplicate OCR charges or overwrite an original.

I use a small table during design reviews:

Path Strength Trade-off Best fit
Browser direct + signed upload App tier stays out of byte path Requires careful CORS and completion reconciliation Large, user-selected files
Server proxy stream Central inspection and uniform clients App bandwidth and connection capacity scale with bytes Mandatory pre-scan or legacy clients
Hybrid Exceptions do not distort the common path Two code paths and two test matrices SaaS with mixed tenants and file sizes

Storage products expose similar primitives with different policy languages. Amazon S3 lifecycle rules can expire incomplete multipart uploads and old objects; Google Cloud Storage and Azure Blob Storage provide their own lifecycle and signed-request mechanisms. Those differences affect implementation details, but the decision rule stays portable: authorize per object, verify completion, isolate tenants by key and policy, and test expiry.

Region and retention governance for abandoned objects

Start with adversarial tests, not a green upload demo. Try a signed URL after expiry, change the object key, replay it for another tenant, send an unexpected content type, and request a sibling prefix. Check that each attempt is denied and that logs contain an upload id without leaking the signed query string.

Keep original files in a private tier and expose downloads through a separately signed, read-only URL with a shorter lifetime. Lifecycle policies should move cold originals to cheaper storage only when legal retention allows it, then delete both originals and derivatives together. AWS documents lifecycle management as a policy on objects and versions, which is a useful reminder that deletion is an automated control, not a cron job someone remembers to run.

The catch is operational complexity. Direct upload is not suitable when your compliance boundary requires every byte to pass through a malware scanner before it lands, or when a partner cannot follow a signed-request flow; stick with a proxy for that path. Conversely, a proxy is a poor default for very large files when throughput and app isolation matter. Keep both paths behind the same upload state machine and observability fields so the exception does not become a second product.

Sources

原文:https://www.a8q9.cn/en/article/receipt-pipelines-browser-uploads-proxy-streams-and-signed-urls-for-private-stor-78d533.html

相关文章