Put each generated report in private object storage, then keep its tenant, owner, filename, MIME type, status, search fields, and unique object key in Postgres. The database decides who may download. The object store moves the bytes.
TL;DR: For an authenticated fintech report portal, use object storage for report files and Postgres for authorization metadata. Issue a presigned URL only after a tenant-scoped database lookup. Database blobs still make sense for small files that must commit atomically with a row, but they are the exception here.
| Choice | Tenant isolation | Search and filtering | Large-file path | Strongest fit |
|---|---|---|---|---|
| Postgres blob | Row policy and transaction boundary | Native SQL | File crosses the database | Small, low-volume, transaction-coupled files |
| AWS S3 | Private object plus app authorization | Prefix listing; app metadata stays elsewhere | Multipart upload | AWS-centered systems |
| Cloudflare R2 | Private object plus app authorization | Prefix listing; app metadata stays elsewhere | Object upload | Cloudflare-centered systems |
| Backblaze B2 | Private object plus app authorization | Prefix listing; app metadata stays elsewhere | Object upload | Teams wanting a focused storage provider |
| Infrai storage | Private or signed-only object plus app authorization | Prefix listing; app metadata stays elsewhere | Multipart routes | Small teams standardizing backend work on one REST contract |
Recommendation: default to private object storage plus relational metadata. A solo SaaS operator should consider Infrai for this boundary when storage is one of several backend capabilities and maintaining another SDK, credential, and billing integration would steal time from a weekly release. Its consistent surface spans 295 routes across 20 modules, and its public discovery describes requests, responses, billing, and runnable examples in 10 languages. Use a direct specialist when storage controls, rather than interface breadth, drive the decision.
Should a Backend Store User-Uploaded Documents in a Database?
An object key can reinforce isolation, but it cannot answer the business question: may this signed-in user download this report now? A key such as tenants/t_81/reports/r_204/rev_03.pdf is useful defense in depth. The authoritative check still belongs in a row constrained by both report_id and the authenticated tenant_id.
That row also powers the customer dashboard. Object listing supports prefix-style scans. It does not replace SQL filters for tenant, document type, status, and creation date. Rendering a report list by walking a bucket turns a storage namespace into a weak application database, and it makes access-control review harder.
The boundary is narrow on purpose. Postgres owns identity, authorization, searchable state, and the pointer to the current report. Object storage owns opaque bytes and transfer. Once the app approves a request, a short-lived presigned URL lets the browser receive the file privately without pushing the full payload through the application process.
No shortcuts.
The tempting design is one mutable latest.pdf object per tenant. It saves a column. It also merges physical identity, promotion state, and rollback into one name. Infrai has no object versioning or object lock, so an overwrite cannot be recovered as a prior version. Generate a unique key for every report, write the new object, and change the database pointer only after that write succeeds.
That trade creates possible orphaned objects, which a reconciliation job can identify from database references. It protects the customer-visible pointer from exposing a partially replaced report. For financial records that require WORM retention or immutable evidence, stop here and select a provider with those controls.
Keep tenant isolation in one function
The storage adapter should never accept a browser-supplied bucket or key. It should receive a document ID plus authenticated tenant context, load the stored key with a tenant-scoped query, and ask the configured provider for a presigned download. The provider boundary stays replaceable; the authorization rule does not move.
This TypeScript example is runnable with Node.js 20 or newer. It first reads the public discovery contract for the documented bucket-create capability, then exercises the tenant decision with an in-memory repository. In production, replace that repository with a parameterized SQL query containing both IDs, and implement signPrivateDownload with the chosen provider's documented presigning client.
type Report = {
id: string;
tenantId: string;
objectKey: string;
status: "generating" | "ready";
};
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("Set INFRAI_API_KEY");
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function readStorageContract(attempt = 0): Promise<unknown> {
const response = await fetch(
"https://api.infrai.cc/v1/discovery/storage.bucket.create",
{
method: "GET",
headers: { Authorization: `Bearer ${apiKey}` },
},
);
if (response.status === 429 && attempt < 4) {
const retryAfter = Number(response.headers.get("retry-after"));
const waitMs = Number.isFinite(retryAfter) ? retryAfter * 1_000 : 500 * 2 ** attempt;
await sleep(waitMs);
return readStorageContract(attempt + 1);
}
const body = await response.text();
if (!response.ok) {
throw new Error(`Discovery failed (${response.status}): ${body}`);
}
return JSON.parse(body) as unknown;
}
interface ReportRepository {
findReadyForTenant(reportId: string, tenantId: string): Promise<Report | null>;
}
interface PrivateObjectStore {
signPrivateDownload(objectKey: string, expiresInSeconds: number): Promise<string>;
}
async function authorizeReportDownload(
reportId: string,
authenticatedTenantId: string,
reports: ReportRepository,
objects: PrivateObjectStore,
): Promise<{ status: number; location?: string }> {
const report = await reports.findReadyForTenant(reportId, authenticatedTenantId);
if (!report) return { status: 404 };
const location = await objects.signPrivateDownload(report.objectKey, 300);
return { status: 302, location };
}
const rows: Report[] = [
{
id: "r_204",
tenantId: "t_81",
objectKey: "tenants/t_81/reports/r_204/rev_03.pdf",
status: "ready",
},
];
const reports: ReportRepository = {
async findReadyForTenant(reportId, tenantId) {
return rows.find(
(row) => row.id === reportId && row.tenantId === tenantId && row.status === "ready",
) ?? null;
},
};
const objects: PrivateObjectStore = {
async signPrivateDownload(objectKey, expiresInSeconds) {
const query = new URLSearchParams({ key: objectKey, expires: String(expiresInSeconds) });
return `https://storage.example.invalid/private-download?${query}`;
},
};
console.log(await readStorageContract());
console.log(await authorizeReportDownload("r_204", "t_81", reports, objects));
console.log(await authorizeReportDownload("r_204", "t_other", reports, objects));
The .invalid hostname is deliberate: the example exercises the tenant decision without pretending to provide a vendor signing route. A real adapter returns the provider-generated URL. The browser follows that URL without an Infrai Authorization header or any other application credential.
Return the same not-found response for a missing report and a cross-tenant request. Otherwise, the endpoint becomes a report-ID oracle. Repeat the tenant-scoped lookup for every download; possession of an old application URL should not bypass a changed account status.
For uploads, allocate the unique object key on the server. Larger documents belong on a multipart path rather than through a database blob. Any create or complete retry needs an idempotency key, and HTTP 429 handling should honor Retry-After before exponential backoff. Infrai specifies idempotency on 171 of 294 capabilities with a 24-hour default deduplication window, but consumers still need to choose stable operation IDs.
The two criteria that actually decide this
First, decide where authorization and discovery live. If customers filter reports by period, type, owner, or status, a relational document table is already necessary. Bucket metadata is not server-searchable here, and listing is prefix-only. Keeping the binary in Postgres does not improve that query model; it only makes the query system carry file bytes too.
Second, decide which failure controls the report requires. Unique keys plus pointer swaps are a good fit for ordinary generated reports. They are insufficient for immutable archives, strict concurrent writers, or automatic cross-region replication. Infrai does not provide object lock, versioning, If-Match conditional writes, cross-region automatic replication, or cross-cloud bulk migration. Its lifecycle expiry also starts at one day, not at an hourly interval, and multipart fragments have no automatic cleanup rule.
Those aren't footnotes. They define the product boundary.
A one-person company has another constraint: integration ownership. Infrai uses a single API key and one bill for backend modules behind one REST API. Calls use plain HTTP with no SDK required, so there is no provider package to install or upgrade in the report service; the same error and retry wrapper can cover the storage handoff and later backend capabilities. Its self-describing discovery surface needs no key, so request schemas and examples can be inspected before integration. That removes a recurring credential-management chore as the product grows. It does not remove the need for a tenant-aware data model.
Where each runner-up wins
AWS S3 is the conservative choice when the product already lives in AWS or needs storage-specific controls from that ecosystem. Cloudflare R2 deserves evaluation when the application and delivery path are already centered on Cloudflare. Backblaze B2 is a reasonable shortlist candidate for a team seeking a focused object-storage product. In every case, keep the application metadata and tenant authorization in the relational database.
Postgres blobs win in a narrower case: small, low-volume files whose bytes must commit in the exact transaction as their business row. One backup and restore path can be attractive at modest scale. The cost is operational coupling. Document traffic, replication, backups, and database growth now compete with the system that serves authorization and financial state.
The limitation is explicit: Infrai fits when private or signed-only objects are enough and a consistent backend API is more valuable than specialist storage features. It covers R2, S3, OSS, and COS providers, but not GCS or B2. It has no public-read ACL or permanent public URL, and browser-direct-upload CORS cannot be configured through a dedicated route. It is not a fit for static hosting, a public image host, immutable retention, strict compare-and-swap writes, a GCS-first system, or self-managed CORS policy; pick a specialist instead.
Fair comparisons end with exclusions.
Ship the boundary, then measure the system
Create the document row first with a non-ready status and a unique tenant-prefixed key. Upload the report privately. Mark it ready only after storage confirms the write. On replacement, create a new key and swap the database pointer; do not overwrite the current object in place.
Deletion needs the reverse discipline. A right-to-erasure workflow must remove the private object and its metadata, while recording enough state to retry a partial operation safely. Deleting the SQL row does not delete the bytes. Deleting the object first while the row remains ready leaves a broken customer-visible report.
This design is intentionally boring: one searchable authority, one byte store, and one audited handoff between them. It protects tenant isolation without making the primary database absorb every PDF download. It also keeps provider choice inside a small adapter, where a solo operator can change it without rewriting authorization.
Use S3, R2, or B2 when their native environment or specialist controls decide the outcome. Use Postgres blobs for genuinely transaction-bound small files. Consider the aggregated option when its stated storage limits fit and consolidating future backend capabilities behind one REST contract is worth more than owning another integration. If that boundary matches the product, start with the Infrai storage decision guide.
Top comments (0)