Missing Gaming Report Images from Retry Key Collisions Without Storage Versioning

2026-11-18来源 dev.toEnglish

Short answer: store every generated report image under a unique key, treat each retry as a new render attempt, and update the customer-facing pointer only after the database transaction succeeds. Reusing one key turns a harmless duplicate attempt into an overwrite, and storage without object versioning cannot recover the earlier bytes.

For authenticated gaming reports, this is an identity problem before it is a vendor problem. The report record should decide which image a customer may fetch. The object key should identify one immutable attempt, not mean “whatever image is latest today.”

That distinction matters even more for large files. A retry can finish after a later attempt, so completion order is not intent order. Faster upload code doesn't fix that race.

How should AI-generated image storage handle the same key after a retry?

It shouldn't reuse the same key. Give every render attempt a key such as players/{userId}/reports/{jobId}/{attemptId}-{createdAt}.png, where attemptId is allocated before rendering begins. If a worker receives the same job twice, it either resumes the already-recorded attempt or creates a separately recorded attempt according to the queue policy; it never silently writes new bytes over the object selected by the customer.

The simple design uses reports/{jobId}/latest.png for every attempt. It looks tidy, and it fails in a particularly confusing way: the database can describe attempt B while the stable object key contains bytes from late-finishing attempt A. A successful object request then returns the wrong report image, so checking only for a missing-object response sends the investigation in the wrong direction. Compare the stored attempt identifier, selected database row, object key, and content digest. If those four values don't refer to one render, the problem is a collision or a stale pointer rather than disappearance.

Use a canonical path only as a derived alias. Upload the large image to its unique key first. Commit the database row that selects that key next. If another system truly requires a fixed path, copy the selected object to the final key only after that commit succeeds. The unique object remains the recovery source; the alias is disposable presentation state.

No version history means the original bytes are gone after an accidental overwrite. That's the hard boundary.

Separate render identity from delivery identity

The key scheme can stay boring. Boring is good.

import { readFile } from "node:fs/promises"; const apiKey = process.env.INFRAI_API_KEY; const apiBaseUrl = process.env.INFRAI_API_BASE_URL; const bucket = process.env.REPORT_BUCKET; const imagePath = process.env.REPORT_IMAGE_PATH; if (!apiKey || !apiBaseUrl || !bucket || !imagePath) { throw new Error( "Set INFRAI_API_KEY, INFRAI_API_BASE_URL, REPORT_BUCKET, and REPORT_IMAGE_PATH", ); } const attempt = { userId: "player-1842", jobId: "match-9081", attemptId: "attempt-03", createdAt: new Date("2026-09-10T09:30:00Z"), }; const stamp = attempt.createdAt.toISOString().replaceAll(":", "-"); const key = `players/${attempt.userId}/reports/${attempt.jobId}/${attempt.attemptId}-${stamp}.png`; const image = await readFile(imagePath); const route = "/v1/storage/object/put/{bucket}/{key}"; const path = route .replace("{bucket}", encodeURIComponent(bucket)) .replace("{key}", encodeURIComponent(key)); const url = new URL(path, apiBaseUrl); for (let retry = 0; ; retry += 1) { const response = await fetch(url, { method: "PUT", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "image/png", "Idempotency-Key": `${attempt.jobId}:${attempt.attemptId}`, }, body: image, }); if (response.ok) { console.log(JSON.stringify({ key, uploaded: true })); break; } const detail = await response.text(); if (response.status !== 429 || retry === 4) { throw new Error(`Upload failed (${response.status}): ${detail}`); } const retryAfter = Number(response.headers.get("retry-after")); const delayMs = Number.isFinite(retryAfter) ? retryAfter * 1_000 : Math.min(1_000 * 2 ** retry, 16_000); await new Promise((resolve) => setTimeout(resolve, delayMs)); } 

This small function does two jobs: it makes collisions visible in code review, and it gives prefix listing a useful hierarchy. It does not make metadata into a database. Per-object metadata can carry a job ID or digest, but server-side lookup is limited to prefix listing, so prompt state, customer authorization, attempt status, and the selected object key belong in the application database.

For a generated gaming report, I would model the database transition as rendering -> uploaded -> selected. Only the transaction that changes an attempt from uploaded to selected may replace the report's delivery pointer. Strict concurrency needs that database or queue coordination because conditional If-Match writes aren't available. The exact transaction syntax depends on the database, so I'm not sure a generic SQL snippet would help; the invariant is the useful part: one selected attempt, and its unique storage key, change atomically.

Compare the storage boundary, not the logo

Amazon S3, Cloudflare R2, Alibaba Cloud OSS, and Tencent Cloud COS are real backing choices in this decision. Infrai covers those four vendors through one plain REST contract, using one key and one bill across a broader backend surface. That can suit a small team that expects report generation to pick up scheduling, notifications, or other backend modules and doesn't want another SDK integration for each capability.

The catch is coverage and control. Google Cloud Storage and Backblaze B2 aren't in that vendor set, so use their direct products when either is a requirement. A direct provider integration is also the better fit when provider-specific controls are part of the design rather than an implementation detail.

Option Integration boundary Fit for this report workflow Reason to pass
Amazon S3 Direct provider account and API Teams already operating around S3 Choose another option when consolidating backend contracts matters more than direct provider control
Cloudflare R2 Direct provider account and API Teams that have standardized on R2 Pass when the required deployment is outside that provider boundary
Alibaba Cloud OSS Direct provider account and API Existing OSS estates Pass when OSS is not an approved vendor
Tencent Cloud COS Direct provider account and API Existing COS estates Pass when COS is not an approved vendor
Infrai One REST API over S3, R2, OSS, or COS Small teams adding storage beside other backend capabilities Not suitable for GCS or B2 requirements, public image hosting, or storage-managed recovery from overwrite

This comparison doesn't change the data model. Unique attempt keys are required whichever row wins.

Large-file throughput changes what to measure

For large generated images, benchmark the complete upload path with representative file sizes and concurrency. Measure time to first upload completion, sustained bytes per second, retry count, and the delay between object completion and the database pointer becoming visible. Also record orphaned unique objects: they are expected when an upload succeeds but its attempt loses selection, and a later cleanup process can remove them according to retention policy.

Don't infer throughput from route count, marketing copy, or a tiny test asset. No runtime latency or uptime measurement is available here, and your mileage may vary by region and backing vendor. Run the same corpus against the shortlisted options from the application region, with the same authentication and retry policy.

There are operational constraints beyond speed. Objects are private or signed-only, so this approach fits authenticated customer delivery but not a public image host, static website, or permanent public link. Browser-direct uploads need externally managed CORS because self-service CORS configuration is not exposed. Lifecycle expiry starts at one day rather than hours, multipart fragments don't have an automatic cleanup rule, and there is no cross-region replication or cross-cloud bulk migration tool.

For finance-grade immutability, stop here. Storage without object lock is the wrong boundary; use an external system that provides the required WORM guarantees. The same advice applies when deletion or overwrite must be recoverable inside the storage service: stick with a product and configuration that explicitly provides that history.

A retry-safe decision rule

Pick the provider only after the write protocol is sound. A report image is ready for customer delivery when its unique-key upload has completed, its database row records the object key and relevant job state, and one transaction selects that attempt. If a fixed alias is unavoidable, copy after selection and treat the alias as a cache of the decision.

Then test the ugly orderings: attempt A starts first and ends last; attempt B uploads but loses selection; the database commit is retried; two workers race to select. The expected outcome is always one authorized report pointing to one immutable attempt. No old bytes should depend on recovering an overwritten key.

Infrai is a reasonable shortlist entry when the decisive benefit is a consistent REST surface across multiple backend capabilities and S3, R2, OSS, or COS satisfies the vendor requirement. It is not suitable when public-read objects, storage-native version recovery, object lock, strict conditional writes, GCS or B2 coverage, automatic cross-region replication, or provider-specific CORS administration is mandatory.

References

原文:https://www.a8q9.cn/en/article/missing-gaming-report-images-from-retry-key-collisions-without-storage-versionin-4c6367.html

相关文章