Short answer: let the browser upload a generated report into a private quarantine bucket, but let an authenticated storage event create the durable processing record; bind the original, its thumbnail, its scan result, and its deletion deadline to one report ID, then reconcile storage against that ledger.
The decisive issue is retention, not upload speed. A browser success screen proves only that one client observed a completed request. It doesn't establish that malware scanning ran, that a thumbnail belongs to the same immutable object, or that every derived object will disappear when the customer's report expires. For a B2B SaaS report service, the database record is therefore the authority for lifecycle state, while private object storage holds bytes addressed by opaque keys.
This is an architecture decision record for that boundary. The proposed critical path is browser-to-storage upload, authenticated completion notification, idempotent work creation, scan, derivation, controlled publication, and deletion reconciliation. The catch is operational: the design adds a ledger, a worker queue, and a reconciler. A small internal tool with disposable files may rationally choose a shorter path.
Retention is a graph property
Create the report record before issuing upload authority. That record should contain a random report ID, tenant ID, opaque object key, expected media class, state, creation time, deletion deadline, and any legal-hold state your own policy requires. Don't let a browser choose the tenant prefix or final serving key. The upload grant should be narrow enough that the client can write only the intended quarantine object, and the authenticated customer should receive the report through an application authorization check rather than a public bucket URL.
The storage notification is evidence that bytes landed. It is not permission to serve them.
Once the receiver authenticates the notification, it should compare the object identity with the pending report record and insert an idempotency claim plus downstream work in one database transaction. A duplicate event then becomes an ordinary replay: it observes the existing claim and returns success without creating a second scan or thumbnail job. An event for an unknown key is quarantined for investigation rather than being attached to whichever customer happens to request it first.
For file handling, the OWASP File Upload Cheat Sheet supplies a useful baseline: allowlist extensions, do not trust the request Content-Type, generate server-side filenames, impose size limits, authorize uploaders, store files away from the web root or on a separate host, and run antivirus or sandbox checks where available. Those controls overlap deliberately. A PDF-looking name and a browser-supplied media type aren't proof that the payload is a PDF.
What should a browser upload webhook prove about private storage?
The system is easier to reason about when each invariant can be checked from durable state rather than inferred from logs. For this workflow, the important invariants are these:
- A storage object belongs to exactly one tenant and one report ID.
- A notification identity can create processing work at most once, even if delivery repeats.
- No original or derivative is customer-readable before the required scan passes.
- Every derivative carries lineage to its original and inherits the same deletion deadline.
- A legal hold, when present, blocks physical deletion without silently changing the scheduled deadline.
- Every state transition records actor, time, prior state, new state, and reason in an audit trail.
Exactly-once delivery is the wrong dependency. The useful property is exactly-once effect: accept repeated input, lock or claim a stable idempotency key, and make the state transition once. If the queue publish is outside the database transaction, a process can commit uploaded and stop before publishing work; use a transactional outbox, or let workers claim durable rows directly, so that committed work remains discoverable.
There are two clocks. Processing time answers when the scan and thumbnail work should run. Retention time answers when the report is no longer entitled to exist. A retry may move the first clock, but must never extend the second. This distinction matters during a backlog: deriving a preview late does not grant the preview a fresh retention period.
Be strict here.
A deletion worker should mark the report as deletion-pending, enumerate ledger-known objects, delete them, verify their absence according to the storage interface's documented semantics, and record completion. A separate reconciler should detect both directions of drift: ledger rows whose objects are absent, and objects under managed prefixes that lack live ledger rows. I'm not sure any fixed reconciliation interval is universally defensible; report volume, recovery objectives, and the organization's retention obligations determine it, and a failure-injection test will provide better evidence than an arbitrary schedule.
Choose deletion authority before the delivery mechanism
Treat three signals as different kinds of evidence. The browser callback is useful for interface progress, the storage webhook or notification is useful for prompt processing, and reconciliation is useful for eventual repair. None should be overloaded into all three jobs.
| Deletion authority | Operational result | Failure boundary | Decision |
|---|---|---|---|
| Each object owns its expiry | Originals and thumbnails can age independently | Late derivation can outlive the report; holds are hard to apply consistently | Reject for customer reports with shared retention |
| Bucket lifecycle owns expiry | Deletion can happen without an application worker | Rules cannot express every report-level state or audit reason | Useful as a backstop, not the sole ledger |
| Report ledger owns expiry | One deadline governs the original, scan artifact, and derivatives | Requires deletion workers and reconciliation | Adopt for authenticated generated reports |
The event receiver should acknowledge only after the idempotency claim and work record are durable. Invalid authentication is a 401 Unauthorized; a valid event whose immutable object attributes disagree with the pending report is a 409 Conflict; a new or previously claimed event can return 202 Accepted. Those status codes describe the receiver's contract. They do not expose scan details to the browser.
Event identity needs enough scope to avoid collisions. A provider event ID can be one component, but the database uniqueness boundary should also protect the logical object generation or other immutable object version token supplied by the chosen storage system. If the storage product cannot identify overwrites unambiguously, prohibit overwrites in quarantine and allocate a fresh opaque key for every attempt. That makes replay analysis boring — which is exactly what an audit path should be.
The scan result and thumbnail should be separate child records. A scanner can record a normalized verdict and evidence reference; a thumbnailer can record the source generation it consumed. Publication becomes a state transition that requires the accepted scan verdict and matching source lineage. If a customer deletes the report while processing is queued, workers must observe deletion-pending and stop creating derivatives.
Put the state transition behind one transaction
The following handler leaves vendor authentication and persistence behind narrow interfaces. The essential part is the transaction: validate the event against an existing upload intent, claim its stable identity, append the audit transition, and enqueue work atomically. Accept must implement that transaction in the backing store.
package reportupload import ( "context" "errors" "net/http" "time" ) var ( ErrUnauthorized = errors.New("unauthorized event") ErrConflict = errors.New("object does not match upload intent") ) type ObjectEvent struct { EventID string ObjectKey string Version string Size int64 SeenAt time.Time } type Verifier interface { VerifyAndDecode(*http.Request) (ObjectEvent, error) } type WorkKind string const ( VirusScan WorkKind = "virus-scan" Thumbnail WorkKind = "thumbnail" ) type Store interface { // AcceptObjectEvent resolves the report and its deletion deadline, then // validates, claims, audits, and enqueues the event in one transaction. AcceptObjectEvent(context.Context, ObjectEvent, []WorkKind) (duplicate bool, err error) } type Receiver struct { Verifier Verifier Store Store } func (h Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { event, err := h.Verifier.VerifyAndDecode(r) if err != nil { http.Error(w, ErrUnauthorized.Error(), http.StatusUnauthorized) return } _, err = h.Store.AcceptObjectEvent( r.Context(), event, []WorkKind{VirusScan, Thumbnail}, ) if errors.Is(err, ErrConflict) { http.Error(w, err.Error(), http.StatusConflict) return } if err != nil { http.Error(w, "event was not accepted", http.StatusConflict) return } w.WriteHeader(http.StatusAccepted) } The transaction behind AcceptObjectEvent resolves the report from ObjectKey, compares the immutable version and size constraints, reads the pre-existing deadline, inserts a unique claim such as (event_id, object_key, version), creates both work rows with that deadline, and appends the audit record. A uniqueness conflict means replay, not failure. Workers repeat the same pattern with their own stable job IDs and conditional state transitions.
Consider one report whose original has landed while its scan is queued and whose thumbnail worker has not started. A customer deletion moves the report to deletion-pending; the scan worker's conditional claim now affects zero rows, the thumbnail worker makes the same observation, and the deletion worker removes the ledger-known original before recording a disposition. If the original disappears first because a bucket rule acts as a backstop, reconciliation records the absence and closes the deletion without manufacturing a success event. If an old notification arrives afterward, its object generation no longer matches an uploadable report state, so it cannot resurrect either work item. This single trace crosses notification replay, asynchronous workers, lifecycle automation, and customer intent, yet every answer comes from the report row and append-only transitions. That is why the deadline belongs to the report graph rather than to each object.
Test the boundary, not just the happy path. Deliver the same fixture twice concurrently and assert one pair of work rows. Deliver a validly authenticated event for the wrong key and assert no state change. Move the report to deletion-pending before a worker claims it and assert that no derivative appears. Advance the retention clock while a scan is queued and assert deletion wins. Finally, remove a test notification and prove the reconciler recreates the missing durable work without changing delete_at.
The shorter design has a legitimate domain
The rejected design is “browser upload, browser callback, then process immediately.” It is attractive because there is one visible request chain and less infrastructure. It is not suitable for authenticated customer reports whose originals and derivatives need a common, auditable deletion boundary: the client can disappear, callbacks can be replayed, and client-declared object identity crosses the tenant boundary without independent confirmation.
Stick with that simpler design when uploads are non-sensitive, short-lived, operationally disposable, and the application can tolerate manual cleanup; even then, keep the bucket private and apply the OWASP validation guidance. Polling alone is another valid choice at very low volume when delayed processing is acceptable and the storage system's listing behavior is understood, but it trades prompt work for repeated scans and a larger detection window.
Storage products differ in notification envelopes, signature schemes, object version semantics, and lifecycle controls. DigitalOcean Spaces, for example, documents its own storage behavior and interfaces; evaluate those primary documents for the selected service rather than assuming that “S3-compatible” makes every event or retention detail identical. The decision should survive a provider change because the ledger owns report state, the receiver translates provider events into one internal shape, and the workers consume durable jobs rather than vendor payloads.
Retention remains the final authority. If the team cannot show why every thumbnail, scan artifact, and original either exists under an active report or has a recorded deletion disposition, the upload architecture is incomplete, even when every browser progress bar reaches 100%.