A team can wire a cloud image-generation API into a web app in an afternoon. The frontend posts a prompt to a serverless route, the route calls an inference provider, waits for the render, writes the output to a public bucket, and hands back a URL.
In staging, with one tester and a warm model, that looks done. Under real traffic, the same setup leaks upstream spend, exposes customer media through links you can't revoke, and opens direct paths to your database or provider account if a privileged key ends up in the wrong runtime. In practice, those failures compound: slow upstream renders, blind client retries, concurrent balance checks, and permanent object URLs reinforce one another until a minor latency spike turns into a billing and access-control incident.
Why synchronous inference endpoints turn latency into duplicate billing
Cloud image generation is slow and bursty. Even when median latency sits around ten seconds, tail latency under provider load routinely pushes past gateway and client timeouts.
Timeout limits vary widely across runtimes and plan tiers, so it's a mistake to design around one universal number. Amazon API Gateway enforces a default 29-second integration timeout for REST APIs. Regional and Private REST APIs can request a quota increase or use response streaming up to 15 minutes for supported proxy integrations, while Edge-optimized REST APIs remain capped at 29 seconds and HTTP APIs at 30 seconds, returning HTTP 504 when an integration runs long. Supabase Edge Functions impose a 2-second active CPU limit, a 256 MB memory ceiling, a 150-second HTTP request idle timeout, and wall-clock limits of 150 seconds on the Free plan and 400 seconds on Paid plans.
Founders often argue that raising serverless timeouts eliminates the need for background queues. I don't buy that argument for media generation, because raising a server limit doesn't control the path between the browser and your backend. Mobile networks drop mid-request, users refresh tabs that look stuck, and upstream CDNs or reverse proxies close idle sockets anyway.
Once a gateway returns HTTP 504 while the inference provider is still rendering, the client retries automatically or the user clicks Generate a second time. Without request correlation, your backend submits another billed job while the first one keeps running upstream. The OWASP API Security Top 10 (2023) lists unbounded calls to paid third-party integrations under API4:2023 (Unrestricted Resource Consumption) for this reason: a retry loop can burn through an operating budget long before anyone checks the dashboard.
Decoupling intake, credits, and queue claiming in Postgres
A production media endpoint shouldn't wait for pixels. Its job is to authenticate the caller, check rate and credit boundaries, persist a job record, and return HTTP 202 Accepted with a job ID that the client can poll or subscribe to.
Moving work onto an async queue doesn't cut inference costs by itself. Queues smooth traffic spikes and prevent dropped HTTP connections from killing in-flight work, while cost control comes from four concrete boundaries: request idempotency, atomic credit reservation, bounded retries, and upstream spend caps.
Start at the intake boundary with an Idempotency-Key header, following the pattern documented in Stripe's idempotent request guide. The client generates one key per logical generation attempt, and the database enforces UNIQUE (user_id, idempotency_key) on the jobs table so network retries return the existing job rather than queuing a duplicate render.
Next, check how you deduct credits. Reading a user's balance in application code with a SELECT and updating it later fails under concurrency: under PostgreSQL's default READ COMMITTED isolation, two parallel requests read the same starting balance and both pass the check. Teams often debate whether to deduct credits up front and refund on terminal failure, or charge only after an image completes. Post-charging feels friendlier in the UI when upstream providers flake, yet it leaves you exposed to concurrent balance races and unbilled upstream spend during retries. I would reserve credits atomically inside the same database transaction that inserts the job row, and record an explicit compensating refund only when a job reaches a terminal failed state.
Another recurring debate is whether to run the job queue in Postgres or introduce SQS, BullMQ, or Temporal right away. For an early-stage product, I would keep the queue in Postgres until throughput genuinely forces a separate broker. Keeping the credit ledger and job state in one ACID transaction avoids a whole class of partial-failure bugs where a message is queued after a credit rollback, or credits vanish without a queued job. PostgreSQL supports SELECT ... FOR UPDATE SKIP LOCKED so multiple workers can claim queued rows without blocking one another. Just don't reuse that query pattern for reporting: the PostgreSQL SELECT documentation explicitly notes that SKIP LOCKED produces an inconsistent view meant for queue consumers.
-- 1. Enforce idempotency at the schema boundary
CREATE TABLE media_jobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL,
idempotency_key text NOT NULL,
status text NOT NULL DEFAULT 'queued',
provider_job_id text UNIQUE,
storage_path text,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (user_id, idempotency_key)
);
-- 2. Reserve credits and enqueue in one transaction
BEGIN;
INSERT INTO media_jobs (user_id, idempotency_key)
VALUES ($1, $2)
ON CONFLICT (user_id, idempotency_key) DO NOTHING
RETURNING id;
-- Only deduct when a new job row was actually inserted.
-- If zero rows return here, roll back and reject the request.
UPDATE accounts
SET credits = credits - $3
WHERE id = $1 AND credits >= $3
RETURNING credits;
COMMIT;
-- 3. Worker claims the next queued job without blocking peers
BEGIN;
SELECT id FROM media_jobs
WHERE status = 'queued'
ORDER BY created_at
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- Mark 'processing', commit, then invoke the upstream provider
COMMIT;
When the insert returns zero rows, skip the deduction and return the existing job for that (user_id, idempotency_key) pair. When a new row is inserted and the UPDATE accounts statement returns zero rows, roll back the transaction and reject the request before any worker sees it.
Database-level quotas still aren't enough on their own if someone registers disposable accounts or a broken worker loops forever on a provider 500. Pair atomic ledgers with per-account and per-IP rate limits that return HTTP 429 Too Many Requests with a Retry-After header, cap worker concurrency and retry counts with exponential backoff into a dead-letter state, and set hard monthly spend ceilings or billing circuit breakers directly in the upstream provider console.
Securing provider callbacks, downloads, and API keys
Once a worker submits a render request, you either poll the provider or accept asynchronous webhooks. Webhooks free up worker slots while the model renders, though they require a hardened public endpoint and a fallback reconciliation poller for callbacks that arrive late or go missing.
A common mistake is assuming an HMAC signature check finishes webhook security. RFC 2104 defines HMAC for message integrity and authenticity, not replay defense or duplicate suppression. Following the OWASP Webhook Security Cheat Sheet and Stripe's webhook verification model, enforce strict payload size limits and compute HMAC-SHA256 over the exact raw, unparsed HTTP request body bytes before JSON middleware alters whitespace or key ordering. Compare digests in constant time using crypto.timingSafeEqual in Node.js or hmac.compare_digest in Python to mitigate timing side channels.
On top of signature verification, sign a timestamp alongside the payload and reject requests outside a narrow tolerance window (Stripe defaults to 5 minutes) to limit replay attacks. Finally, deduplicate by unique event ID and guard your database update with a state check (WHERE provider_job_id = $1 AND status = 'processing'), because provider retries carry fresh timestamps and valid signatures. Without that state guard, duplicate or out-of-order callbacks can overwrite finished outputs or trigger post-processing twice. I cover this same replay and deduplication boundary in more detail in the Stripe webhook idempotency guide.
import crypto from "node:crypto";
export function verifyWebhookSignature(
rawBody: Buffer,
timestampHeader: string,
signatureHex: string,
secret: string,
toleranceSeconds = 300
): boolean {
const ts = Number(timestampHeader);
if (!Number.isFinite(ts)) return false;
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - ts) > toleranceSeconds) return false;
if (!/^[0-9a-f]{64}$/i.test(signatureHex)) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${ts}.`)
.update(rawBody)
.digest();
const provided = Buffer.from(signatureHex, "hex");
// timingSafeEqual throws if buffer byte lengths differ
if (provided.length !== expected.length) return false;
return crypto.timingSafeEqual(expected, provided);
}
Keep signing secrets isolated per webhook integration, support multiple active secrets during rotation, and keep every server credential out of source control, client bundles, logs, and error telemetry, as outlined in the OWASP Secrets Management Cheat Sheet. If your stack runs on Supabase, pay close attention to the separation in the Supabase API Keys documentation: publishable and anon keys map to database roles that enforce Postgres Row Level Security (RLS), whereas secret and service_role keys use a role with the BYPASSRLS attribute and belong strictly inside trusted workers or server routes.
Don't store or proxy raw output URLs returned by third-party inference APIs either. Those links frequently expire on the provider's schedule or sit on public CDNs without tenant scoping. Have your worker fetch the generated image from an allowlisted provider host (so an attacker can't turn your worker into an SSRF proxy), verify Content-Type and a maximum byte size, and stream the bytes directly into your own private bucket under a tenant-prefixed key such as tenant_id/job_id/output.webp.
Why unguessable UUIDs in a public bucket still fail
Teams often defend public storage buckets by arguing that random UUIDv4 object keys can't be guessed. On the brute-force point alone, they're right: UUIDv4 carries 122 bits of randomness, so claiming those paths are trivially enumerable by guessing is misleading.
Real exposure on public buckets happens in more mundane ways. Someone leaves bucket listing enabled (s3:ListBucket or an overly broad SELECT policy), another code path writes sequential or timestamped filenames, or a valid URL leaks through Referer headers, browser history, proxy logs, or shared screenshots. Those failures map directly to API1:2023 (Broken Object Level Authorization) and API8:2023 (Security Misconfiguration) in the OWASP API Security Top 10 (2023).
Revocation is the other problem teams overlook until a customer asks about it. When a user deletes an image or leaves a workspace, a public object URL continues to resolve from caches and saved links.
Private buckets with short-lived signed URLs solve both direct exposure and long-term leakage, provided you watch the credential mechanics on your storage provider. On Amazon S3, turn on S3 Block Public Access at both the account and bucket levels. It overrides public bucket policies and ACLs without interfering with S3 presigned URLs. Watch one operational trap on AWS: when Lambda or ECS mints a presigned URL using temporary STS credentials, that URL stops working as soon as either its explicit expiration elapses or the underlying temporary IAM session token expires, whichever comes first.
On Supabase Storage, private buckets reject public URLs and evaluate RLS policies on storage.objects when createSignedUrl() runs, as documented in Supabase Storage Access Control. Once minted, though, a signed URL behaves like a bearer credential until expiry without re-evaluating RLS. Keep interactive expiries short, roughly 60 to 900 seconds. Issuing 7-day signed URLs brings back most of the revocation risk of a public bucket and breaks expectations when a user deletes an asset or loses workspace access. For deeper Supabase tenant-isolation edge cases, see whether another customer can still access your data when RLS is enabled and the worked guide on Supabase tenant isolation.
Verifying concurrency, callbacks, and storage before launch
A passing happy-path UI test tells you almost nothing about credit races, duplicate callbacks, or bucket isolation. Before putting real customer traffic through a media pipeline, I would run targeted checks against staging and wire a static secret check into CI.
Start with idempotency and database locking. Fire ten concurrent POST requests with the same Idempotency-Key header against your generation endpoint and confirm only one job row is created, credits deduct once, and every response points to the same job ID.
Next, test the SQL locks directly across two psql sessions. Set a test account to credits = 1, open BEGIN; in Session A, and run UPDATE accounts SET credits = credits - 1 WHERE id = 'user_1' AND credits >= 1 RETURNING credits; without committing. Run the same transaction in Session B so it waits on the row lock, then COMMIT; in Session A. Session A should return credits = 0 and Session B should unblock and return zero rows, proving double-spend protection without needing SERIALIZABLE isolation. Verify worker claiming the same way by inserting two queued rows and running BEGIN; SELECT id FROM media_jobs WHERE status = 'queued' ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED; in both sessions before committing; each session should lock a distinct job ID without waiting on the other.
## Confirm 10 concurrent retries create one job and deduct once
seq 1 10 | xargs -P 10 -I{} curl -s -o /dev/null -w "%{http_code}\n" \
-H "Idempotency-Key: verify-key-001" \
-H "Authorization: Bearer $TEST_JWT" \
-X POST https://staging.example.com/api/generations
## Fail CI if privileged server keys appear in compiled client bundles
if grep -rnE 'sb_secret_|service_role|sk_live_|whsec_|AWS_SECRET_ACCESS_KEY' .next/static dist/ 2>/dev/null; then
echo "Privileged key pattern found in client build output" >&2
exit 1
fi
Exercise the webhook handler with four deliberate requests: a validly signed raw payload with a current Unix timestamp (expect 200), the exact same signature after inserting a single space into the JSON body (expect 400 or 401, proving you hash the raw bytes instead of re-serialized JSON), a validly signed payload with a timestamp 10 minutes in the past (expect 400 or 401), and a truncated or malformed hex signature header (confirming a clean 400 or 401 rather than an unhandled ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH crash).
Finish with storage and billing boundaries. Upload a test object to your private bucket and verify that an unauthenticated curl -I to the direct object URL returns HTTP 403 or 400 and that bucket listing is denied. Mint a signed URL with a 5-second expiry, confirm curl -I returns HTTP 200 right away, wait six seconds, and confirm it returns 403 or 400. Finally, check the upstream inference provider console directly to confirm spend alerts and hard monthly ceilings are active.
Keep the limits of these checks in view. Curl probes, two-session SQL tests, and bundle grep scans catch common regressions quickly, but they don't prove that every tenant policy, refund path, or upstream billing rule matches your product design.
Reviewing a Supabase media pipeline before scaling
If your AI media workflow runs on Supabase and you want an independent check before scaling customer traffic, I offer a scoped, read-only technical review covering RLS policies, tenant boundaries, Auth, Storage, Edge Functions, and privileged key handling. You receive a prioritized report with supporting evidence, explicit review limitations, practical recommendations, and a 30-minute walkthrough so your team can decide what to change and implement the fixes cleanly: Supabase security audit.