DEV Community

KiernanBerg3867
KiernanBerg3867

Posted on

Rate-Limited Fintech Export Downloads: Retention, Caching, and Backoff for Node.js SaaS

Short answer: make the export job, not the browser refresh, own a single short-lived download grant; cache that grant until its safety window ends, use bounded backoff for a genuinely rate-limited presign call, and let retention and deletion state decide whether a new link may be issued.

In a fintech product, an export can contain recorded calls, identity evidence, or a settlement report. The application should create the file and metadata, while object storage serves the bytes directly. That keeps a 2 GB download off the Node.js process. The hard part is the control plane: refreshes, retries, and multiple tabs can turn one export into dozens of link requests, while a retention policy may require the object to disappear before a cached URL expires.

What should a Node.js SaaS export page do when signed-link requests hit a rate limit?

Treat the page as a reader of an export record. It asks for a link by stable export ID; the server checks tenant authorization, lifecycle state, and an existing grant before calling storage. A grant has an object key, an expiry, and a deletion deadline. The server never stores the signed URL in a browser-visible database row, and it never uses a user-supplied object key as authorization.

The request path is deliberately boring. One in-flight promise per export prevents a tab storm, and a small server cache absorbs refreshes across tabs. A cache entry must expire before the signed URL does, leaving time to handle clock skew and revocation. If the storage service says “too many requests,” retry the presign operation with jitter, then stop. Retrying a download URL request forever only multiplies pressure.

Keep it boring.

type Grant = { url: string; expiresAt: number; deleteAt: number };

const grants = new Map<string, Grant>();
const inFlight = new Map<string, Promise<Grant>>();

async function getDownloadGrant(exportId: string, now = Date.now()): Promise<Grant> {
  const cached = grants.get(exportId);
  if (cached && cached.expiresAt - now > 60_000 && now < cached.deleteAt) return cached;
  const pending = inFlight.get(exportId);
  if (pending) return pending;

  const work = (async () => {
    const record = await loadExportForTenant(exportId);
    if (record.state !== "ready" || record.deleteAt <= now) throw new Error("export unavailable");
    for (let attempt = 0; attempt < 3; attempt += 1) {
      try {
        const grant = await presignObject(record.objectKey, 300);
        const value = { url: grant.url, expiresAt: now + 300_000, deleteAt: record.deleteAt };
        grants.set(exportId, value);
        return value;
      } catch (error) {
        if (!isRateLimited(error) || attempt === 2) throw error;
        await sleep((2 ** attempt) * 200 + Math.floor(Math.random() * 150));
      }
    }
    throw new Error("unreachable");
  })();
  inFlight.set(exportId, work);
  try { return await work; } finally { inFlight.delete(exportId); }
}
Enter fullscreen mode Exit fullscreen mode

The cache is an optimization, not evidence of access. Every call still resolves the export through the tenant-scoped record. That distinction matters when an account is closed: mark the export for deletion, reject new grants immediately, and let a worker remove the object and record the result. A URL already handed to a browser may remain usable until expiry, so choose the grant lifetime to fit the policy rather than promising instant revocation.

How do retention and deletion change caching and retry backoff?

Retention is a deadline, not a label. Store createdAt, retainUntil, deleteAt, and a lifecycle state such as generating, ready, deleting, or deleted. The presign path allows ready only when now < deleteAt; the worker claims deleting with an idempotency key, removes the object, and records a tombstone. A refresh racing that transition gets a consistent denial instead of a fresh URL.

This is where a tempting “cache for an hour” fix fails. If policy says seven days but a legal hold ends tomorrow, an hour-long grant is already too long. Conversely, a five-minute grant can make a 20-minute download fail midway if the storage service enforces expiry at request time. Your mileage may vary with object size and client network; measure completion time before choosing the window.

Backoff belongs around the presign control call, not around a byte stream that may already be transferring. Honor a Retry-After value when supplied, cap total wait, and surface a stable “try again” state to the page. Do not let each browser tab run its own exponential sequence.

Which failure modes should the export workflow test before release?

I test this with a synthetic tenant containing one 2 GB recording and a deletion deadline one minute away. First I open six tabs, then force a refresh in each. The expected result is one storage call and six cache reads. Next I return a rate-limit response twice; the shared promise backs off twice and succeeds on the third attempt. Finally, I mark the export deleting while a tab is open; no new grant is issued, and the worker's repeated delete is harmless. The useful detail is what the logs say during that minute: the first request creates the promise and records the tenant-scoped object key, the five followers attach without creating network work, and the cache entry is stamped with both URL expiry and the earlier deletion deadline. When the first retry receives a Retry-After: 1 hint, the worker waits one second rather than applying its local 200 ms floor; when the second retry succeeds, all six callers receive the same expiry timestamp. If deletion wins the race after that response, the next refresh still checks the database state and refuses a new grant, while the already-started byte transfer is allowed to finish according to the chosen policy. This test catches a subtle accounting bug: counting browser clicks instead of presign calls makes a healthy single-flight path look abusive, while counting only successful calls hides a rate-limit storm.

That race is the test.

Also test a crashed worker after the storage delete but before the database commit, duplicate export-complete events, a tenant mismatch, an expired grant, and a client that resumes a partial download. Log export ID, tenant ID, state transition, storage request count, and decision reason, but never the signed URL. Metrics should show presign calls per export, cache-hit ratio, rate-limit responses, deletion age, and download completion latency.

The operational checklist is short prose: set a cache TTL below URL expiry; key every record by tenant and export ID; cap retries; honor server hints; make deletion idempotent; alert on exports past deleteAt; and run a daily reconciliation that compares ready records with storage metadata. Keep the byte path direct and the policy path auditable.

The catch is that this design is not suitable when users need permanent public links, offline sharing with unknown recipients, or legal erasure within milliseconds. Use a different distribution model, such as a managed file system or a customer-controlled archive, when those requirements outweigh scoped, expiring access. Stick with direct object delivery when retention evidence and tenant isolation are the primary risks.

Sources

Top comments (0)