DEV Community

Faelvorn538072
Faelvorn538072

Posted on

Object Storage Retention: 4 Direct Browser Upload Gates with Presigned URLs for SaaS

Short answer: keep signed support documents in private, region-aware object storage, and make the deletion deadline part of the upload record before you issue a presigned URL. The browser should send bytes directly; your API should own authorization, retention state, and proof of deletion.

I learned to treat an upload as a workflow, not a successful click. A green progress bar is not evidence that the database has an object, and an object is not evidence that the retention worker has deleted it. Those are separate state transitions. When a queue is late or delivers a message twice, the design must still converge on one answer: keep the document until its deadline, then remove it everywhere your policy requires.

What should browser direct uploads and presigned URLs guarantee?

The presigned URL is a short-lived capability. Scope it to one object key, one method, an expected content type, and a bounded size. Do not put storage credentials in JavaScript. The API first authenticates the agent, checks the customer-support case, and derives delete_after from policy; the client never gets to choose another tenant prefix or extend that date.

Use an opaque key such as org_184/case_7319/attachment_8f2d.pdf. The filename belongs in metadata for display. It should not determine authorization, because names are easy to guess and easy to collide. Keep the bucket or container private and issue a presigned download only after the same case-level authorization check.

Keep it private.

The four gates I use are deliberately boring:

  1. Identity gate: the caller can access the case and is allowed to attach a signed document.
  2. Policy gate: MIME type, byte limit, region, and deletion deadline are validated server-side.
  3. Object gate: completion is confirmed with storage metadata, a checksum, or the multipart completion response.
  4. Expiry gate: a durable job deletes the object and records an auditable result.

That separation matters for US and EU tenants. Region selection is a data-governance decision, not just a latency setting. A bucket in the right geography can still have replicas, backups, exports, or legal holds with a different lifecycle. Write down which copies the deadline covers and who can place a hold that pauses deletion.

The state machine behind a signed support file

I keep an upload row before issuing a URL. Its state starts at pending, then moves to uploaded only after the server confirms the object. A failed browser request can leave an abandoned key; a scheduled sweeper can remove pending rows and their objects after a short grace period.

Here is a compact Go example. The interface is intentionally generic so the authorization and retention decisions remain visible even when the storage SDK changes.

package uploads

import (
    "context"
    "crypto/rand"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type Presigner interface {
    PresignPut(context.Context, string, string, int64, time.Duration) (string, error)
}

type UploadRequest struct {
    CaseID      string `json:"case_id"`
    ContentType string `json:"content_type"`
    Bytes       int64  `json:"bytes"`
}

type UploadRecord struct {
    Key        string
    DeleteAfter time.Time
    State      string
}

func newKey(caseID string) (string, error) {
    b := make([]byte, 12)
    if _, err := rand.Read(b); err != nil {
        return "", err
    }
    return fmt.Sprintf("case/%s/%s", caseID, hex.EncodeToString(b)), nil
}

func CreateUpload(w http.ResponseWriter, r *http.Request, p Presigner, save func(UploadRecord) error) {
    var in UploadRequest
    if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
        http.Error(w, "invalid request", http.StatusBadRequest)
        return
    }
    if in.Bytes <= 0 || in.Bytes > 25*1024*1024 || in.ContentType != "application/pdf" {
        http.Error(w, "file does not match policy", http.StatusUnprocessableEntity)
        return
    }
    key, err := newKey(in.CaseID)
    if err != nil {
        http.Error(w, "could not allocate key", http.StatusInternalServerError)
        return
    }
    deleteAfter := time.Now().UTC().Add(365 * 24 * time.Hour)
    if err := save(UploadRecord{Key: key, DeleteAfter: deleteAfter, State: "pending"}); err != nil {
        http.Error(w, "could not save upload", http.StatusInternalServerError)
        return
    }
    url, err := p.PresignPut(r.Context(), key, in.ContentType, in.Bytes, 10*time.Minute)
    if err != nil {
        http.Error(w, "could not sign upload", http.StatusInternalServerError)
        return
    }
    _ = json.NewEncoder(w).Encode(map[string]any{"key": key, "url": url, "expires_at": time.Now().UTC().Add(10 * time.Minute)})
}
Enter fullscreen mode Exit fullscreen mode

The 365-day value is an example policy input, not a universal retention rule. In production, calculate it from the case type and a versioned policy table. Store the policy version with the row so an audit can explain why a particular date was selected. The URL expiry is independent: a document can be retained for a year while its upload capability lasts minutes.

For large scans or flaky connections, multipart upload lets the browser retry failed parts instead of restarting the whole file. The multipart overview in the S3 documentation describes that protocol; the same operational rule applies to any provider: persist an upload ID, cap its age, and abort abandoned sessions. Do not mark the case complete until the finalization response has been checked.

How do you choose object storage for a US/EU SaaS browser upload?

Start with four tests in a staging account for each intended region. Test CORS preflight from every production origin, including the exact PUT method and headers. Test a browser cancellation followed by a retry with the same idempotency key. Test a duplicate completion message. Finally, test deletion while a worker is restarted halfway through the job.

The comparison should be about behavior your runbook can verify:

Check Pass condition Evidence to keep
Regional placement New keys land in the tenant's approved region request log and bucket policy
Browser access Preflight and upload succeed without exposing credentials browser trace
Integrity Stored checksum or equivalent matches the client declaration object metadata
Expiry Repeated delete attempts converge to an absent object worker log and audit row

Object storage APIs differ in lifecycle rules, multipart limits, event delivery, and checksum support. Those differences are real engineering trade-offs. A managed service may reduce patching work, while a self-hosted cluster can offer tighter placement control at the cost of operating disks, replication, and upgrades. I am not sure which side wins for your team; measure on-call load and recovery time, not just the upload demo.

For a small Node.js SaaS, a thin HTTP adapter is often easier to replace than a deep SDK integration. Keep the application-facing contract to operations such as “create upload,” “confirm object,” and “delete object.” The adapter can translate those operations to the selected provider while tests exercise your policy and state machine.

Deletion is a queue problem, not a cron expression

At the deadline, enqueue a deletion command containing the object key, tenant, policy version, and a deduplication token. A worker should make deletion idempotent: an already-absent object is a successful end state. Retries need backoff and a visible dead-letter path, but they must not silently move the deadline forward. I also run a reconciliation pass that compares due database rows with storage listings, because a queue can lose a message while every individual request still reports success. The pass emits a bounded repair task, records who approved it, and leaves the original deadline untouched. During an incident review, that trail is more useful than a dashboard full of green upload counts.

I have been paged for missed jobs and duplicate deliveries, so I put the evidence beside the state transition. Record delete_requested_at, delete_confirmed_at, attempt count, and the storage response identifier. Alert on age of the oldest due item, not on a fixed number of failures; a quiet queue can still hide a stuck consumer.

Rollback has a narrow meaning here. If a new policy calculation is wrong, stop issuing new uploads under that policy and restore the previous policy version. Do not resurrect files that have already passed an approved deletion deadline. For an in-flight upload, revoke the capability by refusing confirmation and let the sweeper remove the orphan.

The catch is that this pattern is not suitable when your product needs public, cache-heavy media delivery or indefinite legal retention with frequent holds. Use a delivery-oriented CDN path for public assets, and choose a records system when legal hold, immutable retention, and discovery are first-class requirements. Stick with private object storage when the job is bounded access plus a clear, enforceable expiry.

References

Top comments (0)