Short answer: store the document bytes in object storage and keep identity, tenant access, retention state, checksums, and audit events in the database; keep small database blobs only when atomic delivery matters more than independent scaling and direct object delivery.
This is an architecture decision record for a property-management platform that accepts training artifacts from managers and vendors. The decision is driven by access control versus delivery simplicity. Cost matters, but a cheap byte that cannot be erased reproducibly, attributed to the right tenant, or reconciled after an interrupted upload is an expensive liability.
The boundary is intentionally dull: the application owns authorization and lifecycle state, while the object service owns bytes. A document is not considered available merely because some bytes exist. It becomes available only after its checksum, object identity, retention deadline, and committed database state agree.
Decision and failure boundary
Adopt a two-plane design. The control plane is a relational database containing an immutable document identifier, tenant identifier, object key, content length, checksum, retention deadline, legal-hold state, and lifecycle status. The data plane is an object store containing an opaque byte stream under a non-guessable key. A download starts with an application authorization check; only then may the backend issue a short-lived delivery capability or stream the object itself.
Four invariants define correctness:
- One logical upload has one stable idempotency key and one document identifier, even across retries.
- An object is never downloadable until its recorded length and checksum have been verified and the metadata row is committed.
- Every authorization, retention, and deletion transition produces an append-only audit event tied to the document and tenant.
- Erasure is complete only when both the object and its metadata reach a terminal state that a reconciliation job can prove.
The third invariant deserves emphasis. An access log from the byte store can show that a key was fetched, but it generally cannot explain which property-management role authorized the fetch, which lease-training assignment justified it, or which policy version was evaluated. That meaning belongs in the application audit trail. Conversely, the database saying deleted does not prove that bytes disappeared from the data plane. The two records must converge, and a periodic reconciler must report any difference.
This is an exactly-once outcome built from at-least-once operations. Retries are normal.
The primary failure boundary sits between byte upload and metadata commit. If upload succeeds and commit does not, an unreferenced object can remain. If metadata is exposed first and upload does not finish, users can receive a broken document. The first condition is recoverable by a quarantine sweeper; the second violates the availability invariant, so the state machine prevents it. Keep pending objects outside the readable namespace, or require an explicit ready state before delivery.
What must a reproducible retention policy prove?
A retention policy is reproducible when an auditor can take the stored inputs and derive the same decision later. Store the policy version and the event that started the clock, not only a mutable delete_at timestamp. For example, a contractor-safety certificate might be retained from upload, while a tenant handbook acknowledgment might be retained from the end of occupancy. Those are different clocks even when they happen to produce the same date today.
The record should distinguish ordinary expiry, a user erasure request, and a legal hold. GDPR Article 17 defines a right to erasure and also enumerates circumstances in which that right does not apply. The engineering consequence is not an automatic promise to erase every file immediately; it is an explicit decision path whose legal basis, request time, hold evaluation, executor, and completion time are auditable. Compliance counsel must define the policy. The storage system must execute the resulting rule without silently changing history.
Deletion therefore needs a state machine such as active -> deletion_due -> deleting -> deleted, with a separate hold flag or hold record. A worker claims due rows using a lease, requests object deletion with an idempotent operation identifier, verifies the result according to the selected store's contract, writes an audit event, and marks the row terminal. A crashed worker can resume because the document identifier and operation identifier don't change.
Don't turn expiration into a one-shot timer.
Backups are another boundary. A production delete can complete while a protected database backup still contains metadata, and backup restoration can resurrect an old lifecycle state. Document the backup retention window, restrict restores, and require a post-restore reconciliation pass before serving documents. I'm not sure there is a universal retention interval that fits training records across jurisdictions; the unresolved input is the applicable legal and contractual schedule, not a storage benchmark.
How should a backend store large user-uploaded documents?
Choose by transaction boundary and delivery path rather than by a headline unit price. The following comparison treats three mechanisms as architectural options, not as winners in a vendor contest.
| Option | Access-control boundary | Failure and recovery shape | Delivery and cost shape | Suitable case |
|---|---|---|---|---|
| Ordinary database binary column | Same transaction and authorization path as metadata | Backup, restore, replication, and row recovery include bytes | Application and database remain in the byte path; database growth drives operational cost | Small artifacts where atomic write and simple recovery outweigh independent byte delivery |
| Database large-object facility | Database can retain transactional references, but object-specific privileges and cleanup need deliberate handling | Orphan detection and backup behavior depend on the database facility | Reduces some row pressure but still couples file volume to the database estate | Existing database-heavy systems with disciplined large-object operations |
| S3-compatible object storage plus database metadata | Application authorizes; object capability must be scoped and short-lived | Cross-system state requires idempotency, quarantine, and reconciliation | Bytes can travel independently of the application after authorization; request, transfer, retention, and retrieval charges all matter | Growing artifacts, direct delivery, or lifecycle policies that justify the extra state machine |
“Cheapest” is workload-specific. Model stored byte-months, writes, reads, metadata operations, outbound transfer, deletion work, backup amplification, restore time, and staff time for reconciliation. A database blob can be the lower-cost choice for a modest corpus because it avoids a distributed commit problem. Object storage can become the better operational boundary as document size, retention duration, and download traffic grow. Neither statement supplies a universal crossover point; measure it with the actual size distribution and access trace.
Amazon S3, Cloudflare R2, and Backblaze B2 are three real services a team may place on an object-storage shortlist. Their names do not make their contracts interchangeable. Compare the precise API subset, conditional-write behavior, lifecycle semantics, identity controls, consistency guarantees, data-location choices, egress model, and deletion evidence required by this ADR, then preserve those findings as dated test results. A standards-shaped interface lowers migration friction, but it doesn't erase semantic differences.
Access control changes the delivery decision. Proxying every download through the backend gives one obvious enforcement and audit point, and it can be appropriate for highly sensitive or small documents, but it consumes application bandwidth and compute. A time-limited signed capability moves the bytes off that path, although its lifetime becomes a period during which a revoked application permission may not stop an already issued capability. Keep that window aligned with the risk, bind the capability as narrowly as the store permits, and never use a predictable object key as authorization.
For cacheable responses, Cache-Control directives describe how caches may store or reuse a response. Private training artifacts should receive a deliberate policy rather than an inherited default; the correct directives depend on whether the response is personalized and whether any shared cache may retain it. A short-lived download capability and a cache policy solve different problems. Treating them as substitutes creates hard-to-explain exposure.
Critical path in Go
The interface below keeps product details outside the domain model. It also makes the non-atomic boundary visible, which is useful in tests: a fake object store can stop after PutPending, and the next call with the same idempotency key must continue toward the same outcome rather than create a second logical document.
package documents
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"time"
)
type ObjectStore interface {
PutPending(ctx context.Context, key string, body io.Reader) (size int64, checksum string, err error)
Promote(ctx context.Context, pendingKey, finalKey string) error
}
type Repository interface {
Reserve(ctx context.Context, cmd ReserveCommand) (Document, bool, error)
CommitReady(ctx context.Context, id, checksum string, size int64, at time.Time) error
}
type ReserveCommand struct {
TenantID string
IdempotencyKey string
RetentionRule string
RetainUntil time.Time
}
type Document struct {
ID string
PendingKey string
ObjectKey string
Status string
}
type Service struct {
objects ObjectStore
repo Repository
now func() time.Time
}
func (s Service) Upload(ctx context.Context, cmd ReserveCommand, body io.Reader) (Document, error) {
doc, existing, err := s.repo.Reserve(ctx, cmd)
if err != nil {
return Document{}, err
}
if existing && doc.Status == "ready" {
return doc, nil
}
h := sha256.New()
size, storedChecksum, err := s.objects.PutPending(ctx, doc.PendingKey, io.TeeReader(body, h))
if err != nil {
return Document{}, err
}
computedChecksum := hex.EncodeToString(h.Sum(nil))
if storedChecksum != computedChecksum {
return Document{}, errors.New("stored checksum does not match upload")
}
if err := s.objects.Promote(ctx, doc.PendingKey, doc.ObjectKey); err != nil {
return Document{}, err
}
if err := s.repo.CommitReady(ctx, doc.ID, computedChecksum, size, s.now()); err != nil {
return Document{}, err
}
doc.Status = "ready"
return doc, nil
}
Reserve must enforce a unique tenant-and-idempotency-key constraint and return the prior reservation on retry. CommitReady must be an idempotent transaction that changes only the reserved document and appends its audit event. Production code also needs bounded input size, content-type validation based on inspected bytes, malware-scanning state, cancellation handling, and metrics for pending age, checksum mismatch, deletion lag, and reconciliation differences. These aren't incidental upload features; they are gates in the document state machine.
Test the interruption points. Stop after reservation, after byte upload, after promotion, and after metadata commit; retry each case and assert one document identity, one final object, and a coherent audit sequence. Then restore a database snapshot into an isolated environment and run reconciliation against a corresponding object inventory. A design that passes happy-path upload tests but cannot explain restore behavior is unfinished as an operational decision.
Rejected option and its valid use case
The rejected default is storing every training artifact in the primary relational database. The catch is coupling: large-file growth joins transaction logs, replicas, backups, restore exercises, and application delivery in one failure and cost domain. That is not suitable when files dominate database volume or when direct object delivery is an explicit requirement. For this property-training workload, the independent data plane is worth the reconciliation machinery because access decisions remain centralized while byte delivery can scale separately.
Still, keep database blobs when documents are small, infrequently downloaded, and must commit atomically with a business record, especially when the team cannot operate a reliable cross-system reconciler. That is a valid simplification, not an inferior architecture. Likewise, stick with backend-proxied delivery when immediate revocation and a single controlled audit point outweigh bandwidth efficiency; signed capabilities are a deliberate trade, not a default badge of maturity.
The final acceptance test is evidence: can the system show who authorized a document, which retention rule applied, whether the bytes matched at commit, what happened across retries, and whether erasure converged across both planes? If those answers are deterministic, the storage choice is defensible. If they aren't, a lower storage line item does not repair the design.
Top comments (0)