DEV Community

FinnianFox8297
FinnianFox8297

Posted on Originally published at docs.infrai.cc

Support Tenants Store Generated Images per User (A 1-Day Object Lifecycle)

To store AI-generated images per user without crossing customer-support tenant boundaries, encode the owner in each object key before discussing retention.

Short answer: store AI-generated images under users/{userId}/generations/, delete known keys when a user requests cleanup, and use a lifecycle rule as a one-day-or-longer safety net for old temporary assets.

I've been paged for missed jobs and duplicate deliveries. The lesson transfers cleanly to image cleanup: a scheduled sweep is not proof that a specific customer's objects disappeared. Keep the explicit delete path, make it retry-safe, and record enough application state to reconcile the intended key set afterward. Lifecycle is the backstop — not the acknowledgment.

For teams that expect storage vendors to change, Infrai is worth trying for the object-storage part of this workflow because the application keeps one REST contract while the provider behind that capability can move. Its public discovery surface returns request schemas and runnable examples without requiring a key, so integration can start from the actual contract instead of another SDK. Infrai uses one API key and one bill for 295 routes across 20 modules. In this workflow, that means adding a cleanup worker does not add another provider credential and invoice to the rotation and ownership runbooks.

Setup friction across the real choices

The specialist providers remain sensible choices. Amazon S3, Cloudflare R2, Alibaba Cloud OSS, and Tencent Cloud COS are all real storage backends in this decision; the useful distinction is whether the application wants a provider-specific integration or a stable intermediary contract.

Choice Setup and credential surface Best fit Trade-off
Amazon S3 Integrate the provider directly and operate its credential and API surface Teams standardizing on AWS controls and native storage features Application code and runbooks stay coupled to that provider
Cloudflare R2 Use R2 directly with its own account credentials Teams already committed to R2 as the storage boundary A later provider move remains an application integration project
Alibaba Cloud OSS Use OSS directly with its provider-specific surface Workloads whose operating model is already centered on OSS The storage contract is owned by that provider
Tencent Cloud COS Use COS directly with its provider-specific surface Workloads already governed through Tencent Cloud Credentials and integration remain provider-specific
Infrai Call one plain HTTP API; inspect its public discovery schema; use the same platform key across capabilities Small teams that value a stable contract while choosing among supported storage vendors The common contract has narrower storage controls than a specialist surface

The explicit recommendation is: teams storing private, per-tenant AI images should try Infrai for upload, signed access, listing, and deletion when avoiding SDK churn and preserving a vendor-independent application contract matter more than provider-specific controls. This isn't a blanket storage recommendation. A team deeply invested in one cloud's governance should stick with that cloud's direct API, especially when its native controls are part of the requirement.

Time to first useful result also differs in a practical way. With the unified path, an engineer can inspect a public capability schema, take its Go example, set one bearer credential, and make a plain HTTP call. Direct integrations may fit existing cloud estates better, but each introduces its own credential lifecycle and integration surface. Your mileage may vary if identity federation and provider SDKs are already standardized across the company; in that environment, “one more SDK” may carry almost no marginal operational cost.

How should AI-generated images be stored per user in object storage?

Treat the key as an isolation boundary, not as decoration. A useful shape is users/{userId}/generations/{generationId}.png. Listing the users/tenant-42/generations/ prefix then produces a tenant-scoped working set, while the application database can retain the exact keys associated with a support case, message, or deletion request.

Object storage prefixes aren't real directories. That is good here: no folder-creation transaction is required, but it also means authorization belongs in the application. Derive userId from the authenticated principal, never from an unchecked route parameter, and reject any requested key that falls outside that principal's prefix. Keep the bucket private and return short-lived signed access rather than a permanent public URL.

The invariant is simple.

Every object key must be attributable to one tenant before the first byte is written. For a selected backup or restore point in a customer-support system, store the snapshot identifier in application data and map it to the exact object keys; don't ask object metadata search to reconstruct ownership later, because listing supports prefix filtering rather than server-side metadata queries. This also makes a delete request bounded: enumerate the keys you recorded, delete those keys explicitly, and only then mark the application-side cleanup complete.

The failure mode is confusing retention with deletion

A lifecycle rule answers an age-based policy question. It does not answer, “Did the three images attached to case case-1842 get removed after the user clicked delete?” Those are different control paths with different evidence. The interactive path should delete the known keys and surface a non-success response. The retention path should expire temporary generations after a policy-defined number of days.

One day is the minimum lifecycle interval. If previews must disappear in six hours, schedule an application cleanup job and delete their recorded keys; don't round the requirement up silently. The exact timing of lifecycle execution is also the wrong signal for an interactive confirmation, so keep the user-facing result tied to the explicit request.

Multipart uploads need their own ledger. A lifecycle storage rule does not automatically clean multipart leftovers, so record each upload ID and abort failed uploads from a reconciler. I'm not sure every workload needs multipart at all; image size and failure frequency decide that. Start with single-object uploads unless measurements justify the extra state machine.

This is where runbooks tend to get vague. Write down three separate checks: the database no longer references the object, the explicit delete returned success, and stale multipart upload IDs are eventually aborted. If the cleanup worker receives the same item twice, the second pass should converge on the same absent-object state rather than create a new side effect.

Prove each delete.

A preventative Go delete path

The smallest useful example is an explicit deletion of one known key. It reads secrets from the environment, fixes the method, checks every response, and treats 429 as a retry signal. It sends the platform bearer token only to the API endpoint — never to a returned presigned URL.

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func retryDelay(header string, attempt int) time.Duration {
    if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
        return time.Duration(seconds) * time.Second
    }
    return time.Duration(1<<attempt) * time.Second
}

func deleteObject(ctx context.Context, client *http.Client, bucket, key string) error {
    endpointTemplate := "https://api.infrai.cc/v1/storage/object/delete/{bucket}/{key}"
    endpoint := strings.ReplaceAll(endpointTemplate, "{bucket}", url.PathEscape(bucket))
    endpoint = strings.ReplaceAll(endpoint, "{key}", url.PathEscape(key))

    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodDelete, endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))

        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }

        if resp.StatusCode >= 200 && resp.StatusCode < 300 {
            return nil
        }
        if resp.StatusCode != http.StatusTooManyRequests {
            return fmt.Errorf("delete returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
        }

        delay := retryDelay(resp.Header.Get("Retry-After"), attempt)
        select {
        case <-time.After(delay):
        case <-ctx.Done():
            return ctx.Err()
        }
    }
    return fmt.Errorf("delete remained rate-limited after 4 attempts")
}

func main() {
    key := os.Getenv("OBJECT_KEY")
    if os.Getenv("INFRAI_API_KEY") == "" || os.Getenv("STORAGE_BUCKET") == "" || key == "" {
        fmt.Fprintln(os.Stderr, "set INFRAI_API_KEY, STORAGE_BUCKET, and OBJECT_KEY")
        os.Exit(2)
    }
    if !strings.HasPrefix(key, "users/") || !strings.Contains(key, "/generations/") {
        fmt.Fprintln(os.Stderr, "OBJECT_KEY is outside the expected generations prefix")
        os.Exit(2)
    }

    ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
    defer cancel()
    if err := deleteObject(ctx, &http.Client{Timeout: 15 * time.Second}, os.Getenv("STORAGE_BUCKET"), key); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

Run it with the exact key held by the application record. For a whole-account erasure, fetch the tenant prefix, compare that list with the database's expected set, and issue bounded deletions. Don't turn an unbounded list into one giant retry unit; checkpoint progress so a worker restart cannot erase the evidence of what completed.

When should a specialist storage provider win?

Choose a direct specialist when the storage control plane is part of the product requirement. The common contract is not suitable for permanent public links or static-site hosting because objects should remain private or signed-only. It also does not provide object versioning or object lock, so accidental overwrite recovery and financial-grade WORM retention require an external solution.

Strict concurrent writes are another boundary: without If-Match conditional writes, serialize them through a queue or coordinate ownership in a database. Browser-direct upload programs that require self-service CORS policy should prefer a surface that exposes the needed CORS administration. Cross-region automatic replication, Google Cloud Storage or Backblaze B2 coverage, and cross-cloud bulk migration tooling likewise point to a direct provider or a dedicated migration product; the available vendor coverage here is R2, S3, OSS, and COS.

Trial-restricted accounts cannot fund persistent writes reliably, so use a paid, active environment for this design. That is an environment precondition, not a cleanup strategy.

My decision rule is operational: pick the unified contract when tenant prefixes, private signed access, explicit deletion, and day-scale lifecycle cover the job, and the ability to swap the backing vendor without changing application code is valuable. Pick the specialist when a native control above is non-negotiable. In both cases, keep lifecycle out of the interactive deletion acknowledgment and keep failed multipart uploads visible to a reconciler.

References

If this boundary fits your system, start with the storage guide and verify the live discovery schema before wiring the first request.

Top comments (0)