A gaming storage pattern has to treat user documents — PDF receipts, DOCX exports, and invoices — as both immediate downloads and original audit records. That constraint makes a public folder, or a private bucket whose prefixes stand in for database metadata, the wrong center of the design.
Short answer: keep every PDF, DOCX, and invoice object private; put tenant ownership, document state, checksum, retention class, and an opaque object key in database metadata; authorize every upload and download against that row; then issue a short-lived delivery capability only after authorization. This pattern preserves a simple browser flow without turning a path into an access-control rule.
The distinction matters. A key such as tenant-84/invoices/2026/receipt-991.pdf looks organized, but organization is not authorization, and human-readable paths leak business context into logs, support screenshots, and analytics. Use prefixes for operations such as lifecycle grouping or inventory. Don't ask them to decide who may read a receipt.
What should multi-tenant SaaS storage protect in private user document delivery?
The protected unit is not merely a blob. It is the binding among a tenant, a user or service principal, an immutable receipt identity, the exact bytes originally accepted, and every later decision to disclose those bytes. A gaming system that stores purchase receipts therefore needs two linked records: an object containing the original file and a database row containing the security and audit meaning of that object.
Keep the object store private by default. A request for a document should arrive at the application first, where the application resolves the document ID inside the authenticated tenant, checks the caller's role and purpose, and records the decision. Only then should it return a narrowly scoped, short-lived upload or download capability. The client gets delivery simplicity; the application keeps authority.
This also answers the recurring bucket question. A bucket per tenant can be defensible when contractual isolation, separate administrative ownership, or a distinct retention policy requires a hard operational boundary. It is usually a poor default for a large shared SaaS fleet because bucket provisioning, policy drift, inventory, and migrations become tenant-count problems. A shared private bucket with opaque object keys and database-enforced tenant ownership is easier to operate, provided no request can fetch an object by key alone. The catch is explicit: if a regulator, contract, or customer-controlled encryption boundary requires independently administered storage, stick with separate buckets or accounts even though delivery and operations become more involved.
Folder prefixes still have a job. A key shaped like objects/7f/7f43... can distribute inventory work, while a coarse prefix such as retention/finance/... can support lifecycle administration. Neither prefix should contain an email address, player name, order number, or authorization claim. Treat the key as a locator with no business truth attached.
One rule catches most design errors: if changing a database row from tenant A to tenant B would expose tenant A's file, the download path is under-authorized. The handler must constrain the lookup by both tenant and document identity, and the object key must come from the resulting row rather than from caller input.
Small rule. Large consequence.
Audit identity versus object location
The metadata row is the control plane for a user document. At minimum, it needs an application-generated document ID, tenant ID, media type, original display name, opaque object key, byte length, content checksum, processing state, creator, creation time, and retention class. Store the display name for user experience, but never concatenate it into a filesystem-like key. If malware scanning, receipt extraction, or reconciliation produces derived artifacts, give each artifact its own identity and a relation back to the immutable original.
The checksum is not a substitute for access control or a digital signature. It is a practical reconciliation value: after an upload, a worker can verify that the bytes it examined are the bytes associated with the metadata row; during migration, the same value can detect an incomplete copy; during an audit export, it can make accidental substitution visible. The original should not be overwritten by a corrected receipt. Append a new version or derived document and preserve the lineage, because an audit trail that silently rewrites its subject is only an activity log.
Paths lie.
Model authorization independently from location. A policy decision can use tenant membership, role, document classification, ownership, support elevation, and retention status. The storage adapter should receive an already authorized object key and a bounded intent such as read-original or write-pending-upload. It should not receive a user-controlled prefix and infer policy from string comparison.
Audit events deserve the same discipline as ledger entries: identify the actor, tenant, document, action, policy result, request correlation ID, and time; make privileged support access distinguishable from ordinary user access; and reconcile event production rather than assuming a log write happened. Do not record the temporary capability itself. A bearer capability in a log is still a bearer capability.
Should authorization end before the storage adapter?
The following Go boundary keeps that division visible. The exact database and object-store implementations are deployment choices; the contract is the important part.
package documents import ( "context" "errors" "time" ) type Document struct { ID string TenantID string ObjectKey string OriginalName string MediaType string ChecksumSHA256 string State string RetentionClass string } type Repository interface { FindForTenant(ctx context.Context, tenantID, documentID string) (Document, error) AppendAuditEvent(ctx context.Context, tenantID, documentID, actorID, action string) error } type CapabilityIssuer interface { IssuePrivateRead(ctx context.Context, objectKey string, expiresAt time.Time) (string, error) } type Service struct { documents Repository issuer CapabilityIssuer now func() time.Time } var ErrNotAvailable = errors.New("document not available") func (s Service) CreateDownload( ctx context.Context, tenantID string, documentID string, actorID string, ) (string, error) { doc, err := s.documents.FindForTenant(ctx, tenantID, documentID) if err != nil || doc.State != "available" { return "", ErrNotAvailable } if err := s.documents.AppendAuditEvent( ctx, tenantID, doc.ID, actorID, "download_authorized", ); err != nil { return "", err } return s.issuer.IssuePrivateRead(ctx, doc.ObjectKey, s.now().Add(5*time.Minute)) } The deliberately generic error avoids confirming that a document exists in another tenant. The five-minute duration is an example policy, not a universal recommendation; choose a window from file size, client behavior, revocation needs, and threat model, then test it on the slowest supported connection. I'm not sure any single duration is defensible across jurisdictions and enterprise contracts. The retention schedule and audit-event content need review by the people accountable for those obligations, because technical immutability does not determine a legal retention period.
One accepted invoice versus two processing attempts
Uploading bytes and committing metadata cannot be one atomic transaction when the database and object store are separate systems. An exactly-once mindset remains useful, but the implementable boundary is an idempotent state machine with reconciliation. Create a pending document row and an opaque object key first. Issue a write capability tied to that key. After the client finishes, have the application or a worker verify the stored object's expected properties before moving the row to available. Processing consumers must use the document ID plus a processor version as an idempotency key, so a retry does not create a second extracted receipt or a second ledger effect.
Consider one concrete, hypothetical timeline. Tenant t-84 starts document d-991, the database records a pending row, and the service assigns an opaque object key. The browser sends every byte of receipt.pdf, but its network changes before the completion response arrives. The user presses retry. The second request carries the same document ID and idempotency key, so it must resolve to the existing pending row rather than minting another object; meanwhile, a verifier may already be reading the first upload. If the verifier confirms the expected object properties, it advances that row to available with a conditional state update, writes the audit event, and schedules receipt extraction under an idempotency key made from d-991 and the processor version. If the browser's delayed completion request arrives next, it observes available and returns the same document identity. If two workers receive the extraction message, the second sees that the derived artifact for that document and processor version already exists. No component needs to pretend the distributed sequence was one database transaction. Each boundary instead leaves enough durable evidence for a later reconciliation pass to decide which work happened, which work may be repeated, and which transition is still outstanding. Treating the retry as a fresh receipt would create duplicates; treating the missing acknowledgement as proof that no object exists would lose work. The state machine avoids both errors while preserving the first submitted file as the audit original.
Retry it.
Use an explicit transition set, for example pending -> verifying -> available, with terminal quarantine or rejection states where policy requires them. Protect each transition with a compare-and-set condition on the current state or version. A worker that receives the same message twice then observes that the transition already occurred and can return without repeating a derived write. Keep the original object even when parsing fails if the retention policy requires preservation; processing status describes what the system learned, not whether the submitted bytes ever existed.
Browser upload progress is a presentation concern rather than a permission model. XMLHttpRequest exposes upload progress events, which can make large receipt uploads understandable to users, but completion in the browser still must not mark the server-side record as verified. The browser reports transport progress; the backend owns acceptance and state.
Test the awkward edges, not only the happy path: two completion requests for one document ID, a worker retry after committing a derived row, a tenant context that does not match the document, an expired delivery capability, a renamed display file, and a migration that copies bytes but misses metadata. For access-control tests, generate pairs of tenants and assert that every identifier from one pair is unavailable under the other. For reconciliation tests, interrupt each state transition and prove that another run converges without overwriting the original.
Should delivery stay direct or cross an application proxy?
Private does not require proxying every byte through the application. After an authorization decision, a temporary capability can let the browser transfer directly to or from object storage, avoiding an application server that becomes a bandwidth relay. Proxying is still the better choice when content must be transformed inline, every byte must pass through a controlled inspection point, or a temporary bearer link is prohibited. There is no universally best delivery path.
| Delivery boundary | Suitable when | Limitation to accept |
|---|---|---|
| Direct transfer after application authorization | Browsers need straightforward upload or download and bounded bearer capabilities are permitted | The capability lifetime, client storage, and cache behavior become security policy |
| Application proxy | Inspection, transformation, or policy enforcement must remain in the byte path | Application bandwidth and capacity become part of document delivery |
| Separate tenant storage boundary | Contractual administration, encryption ownership, or isolation requires it | Provisioning, inventory, policy management, and migration multiply with tenant count |
Caching needs a deliberate answer because a receipt is sensitive even after access was valid. Responses that pass through the application should use a cache policy appropriate to private data; MDN documents directives including private and no-store and explains that shared caches must not store a response marked private. Temporary object URLs also belong in neither analytics payloads nor persistent client state. Authorization should be re-evaluated when a new capability is requested, so removing a user's role affects future delivery rather than waiting for a stable public URL to disappear.
The access-control versus delivery-simplicity decision can be made with a short hierarchy. Use an application-mediated authorization step in every design. Choose direct transfer after that step when ordinary browser delivery and bounded bearer capabilities are acceptable. Choose an application proxy when inspection or policy must remain in the data path. Choose a separate administrative storage boundary when the tenant's compliance or ownership model requires it.
Costs follow those choices, but they shouldn't lead them. Evaluate stored original bytes, retained versions, request volume, retrieval and network delivery, inventory work, audit-log growth, and the compute used for scanning or extraction. A proxy may add application bandwidth and capacity; direct delivery may increase the importance of capability issuance and cache controls; bucket-per-tenant isolation adds control-plane work. Model costs from an observed receipt-size distribution and retention schedule, then review the model when product behavior changes. An attractive storage unit rate cannot repair a tenant isolation failure.
Reconciled migration batches versus blind object copies
Roll out in an order that keeps old and new records explainable:
- Add the database identity and state machine while the current delivery path still operates. Give new uploads opaque keys and immutable metadata, and resolve reads by tenant plus document ID.
- Backfill older objects in restartable batches. Record source key, destination key, checksum, and migration state, then compare counts and checksums before changing read traffic.
- Shadow authorization decisions without issuing a second download. Move a small tenant cohort to the new resolver and watch denied cross-tenant lookups, pending-state age, verification lag, duplicate processing attempts, and audit-event reconciliation.
- Remove path-derived authorization only after all callers use document IDs and the old key space has been reconciled. Retain a bounded rollback window and restrict access to the migration mapping according to policy.
Prove it.
These are correctness signals, not vanity throughput numbers. Once the mapping has served its operational recovery purpose, dispose of it under the applicable policy. The finished design is deliberately plain: private bytes, database-owned meaning, explicit state, and delivery capabilities that expire. That is a document system an audit can reason about.

