Short answer: put each game's export in a tenant-scoped object key, stream the CSV from an Express job, and issue a short-lived signed download only after the final object write is confirmed. Keep the deletion deadline in durable metadata, separate from the link's expiry.
The page that wakes me up is not “CSV generation failed.” It is a support ticket saying a signed contract downloaded yesterday, after the retention deadline, or that two teams can see the same filename. The useful signal should have fired earlier: an export stuck in uploading, a cleanup cursor that has not moved, or a key whose tenant prefix does not match its owner.
This is a delivery workflow, not a button handler. In a gaming service, legal documents can arrive while a match is active and a tenant can be a publisher, studio, or tournament organizer. The export job must remain isolated when requests retry, workers restart, and a browser closes halfway through a download.
Keep it boring.
What should an Express Node.js export guarantee?
Start with an export record. Give it an opaque id, tenant id, source revision, object key, created_at, delete_after, and a state such as queued, uploading, ready, or expired. The idempotency key belongs to the request semantics, for example tenant_id + report_revision, rather than to a random HTTP retry. A repeated request can then return the existing job instead of producing a second signed document.
The object key should encode an authorization boundary, such as tenants/acme/exports/8f2.../contracts.csv. Treat that prefix as a defense-in-depth check, not as the authorization itself: the database row still decides whether a caller may access the artifact. Never accept a key supplied by the browser and concatenate it into a storage path.
The browser receives a job id first. A status read returns a link only for a ready record whose delete_after is in the future. The response that starts the job should not wait for a multi-gigabyte query; queue it and let the worker own retries. Small files can finish inline, but that is a policy choice based on measured duration, not a promise made by the route.
For downloads, set Content-Disposition: attachment and a safe, quoted filename. The HTTP specification and MDN describe how this header controls presentation and why a server-provided filename must be handled carefully. Keep the original user-visible title in metadata, while the object key stays opaque.
How can Node.js generate a CSV, upload it, and return a signed link safely?
The implementation boundary is intentionally boring: a producer writes CSV bytes, an object-store adapter consumes a reader, and a signer runs after the adapter reports success. This Go example mirrors the same contract an Express worker would implement with streams. It makes backpressure and error ownership explicit without tying the article to a vendor SDK.
package export
import (
"context"
"encoding/csv"
"io"
)
type Store interface {
Put(ctx context.Context, key string, body io.Reader, contentType string) error
SignedGet(ctx context.Context, key string, ttlSeconds int64) (string, error)
}
func UploadCSV(ctx context.Context, store Store, key string, rows <-chan []string) error {
reader, writer := io.Pipe()
writeErr := make(chan error, 1)
go func() {
encoder := csv.NewWriter(writer)
for row := range rows {
if err := encoder.Write(row); err != nil {
_ = writer.CloseWithError(err)
writeErr <- err
return
}
}
encoder.Flush()
if err := encoder.Error(); err != nil {
_ = writer.CloseWithError(err)
writeErr <- err
return
}
writeErr <- writer.Close()
}()
if err := store.Put(ctx, key, reader, "text/csv; charset=utf-8"); err != nil {
_ = reader.CloseWithError(err)
return err
}
return <-writeErr
}
In the worker, mark the row ready only after UploadCSV returns nil and a metadata read confirms the expected byte count or checksum. Then call SignedGet with a short TTL, for example 900 seconds, and write that URL to the status response. A signed URL is a bearer credential; anyone who obtains it can use it until expiry. If every request needs immediate revocation or watermarking, proxy the download through an authorization service and accept the added bandwidth and latency.
CSV data has sharp edges. Escape fields containing commas, quotes, or newlines through a real encoder. Cap query batches and honor backpressure so one tenant cannot exhaust worker memory. Multipart upload is appropriate for large artifacts, but persist the upload id and completed parts; a retry must either resume deliberately or abort and create a new attempt. Overwriting a key that is already being downloaded makes incident analysis painful.
Which retention design survives duplicate jobs and deletion races?
The cleanup worker claims a page of rows where delete_after <= now(), deletes the object, and then marks each row expired. Deletion is idempotent: an object that is already absent satisfies the retention action. Keep an audit record for authorization failures and malformed keys rather than silently advancing the cursor. A transaction around the claim prevents two workers from processing the same row, but the object deletion itself still needs a retry policy.
The recovery path deserves more detail because this is where a clean diagram meets a 03:00 page. Suppose worker A claims 500 expired exports and loses its process after deleting object 217. Worker B must be able to reclaim the other 499 without treating 217 as a fresh violation. Store a per-object deletion outcome, or use a lease with a bounded expiry, then make the next pass compare the recorded key and tenant prefix before issuing a delete. If the storage call times out, do not guess whether it committed: retry an idempotent delete and record the attempt count. Once the object is confirmed absent, mark only that row expired. This gives support a trace from export id to deletion timestamp and leaves a bounded set of rows for the next pass. It also prevents a broad “delete everything under this prefix” operation from crossing tenant boundaries when a malformed record slips through.
There is a subtle race between a download status read and cleanup. Recheck the deadline immediately before signing, and make the status transition conditional on the same row version. If cleanup wins, return “expired” and no URL. This is stricter than hoping a five-minute link TTL will cover a seven-day policy; URL lifetime and object lifetime are different controls.
I once assumed the upload call was the risky part. The harder failure was a worker that committed expired before its delete batch had completed, leaving no way to find the orphaned object. The fix was a deletion result table plus a metric for the oldest unprocessed deadline. Three words: measure the lag.
Where do alerts and tenant-isolation tests catch the page earlier?
Instrument the state machine, not just HTTP status. Useful time series include age of the oldest uploading job by tenant, bytes and rows written, upload duration, signer failures, cleanup lag, and the count of objects whose prefix disagrees with their export row. Sample structured logs with export id and tenant id; never log the signed URL itself.
The false-positive cost matters. A latency threshold set below normal multipart variance trains on-call to mute the page; one set above the deletion deadline lets a document remain available too long. Establish a baseline from production-shaped load, then alert on sustained deviation and on absolute policy breaches.
Tests should include a tenant attempting to read another tenant's id, a retry after the final upload part, a process restart while streaming, a CSV field with a newline, and cleanup racing a status request. Use a fake store that records keys and TTLs, then assert that no signer call occurs for queued, uploading, or expired rows. Your mileage may vary with a storage gateway's maximum signed-link TTL, so expose that limit as configuration and test it during deployment checks.
| Decision | Direct signed download | Authorized download proxy |
|---|---|---|
| Large file bandwidth | Storage service carries bytes | Application carries bytes |
| Revocation | Ends at URL expiry or object deletion | Can revoke per request |
| Audit detail | Log issuance and export id | Log every byte-serving request |
| Best fit | Stable policy, high volume | Strict revocation or watermarking |
The catch is that tenant isolation and retention are coupled. Direct links are unsuitable when policy requires per-click authorization after issuance; use a proxy then. For ordinary export delivery, the simpler path is a tenant-checked state machine, a confirmed write, and an observable cleanup worker.
References
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Disposition
- https://www.rfc-editor.org/rfc/rfc9110
- https://aws.amazon.com/s3/pricing/
Top comments (0)