AI API Security: Best Practices for Production
Protect your AI integration with these essential security practices — from API key management to rate limiting and input validation.
Read articleBuild an auditable media-job lifecycle with stable identities, versioned inputs, durable events, protected artifacts, and honest delivery records.

A customer sees the wrong image in an export and asks which prompt produced it. The application has a request log, the provider has an operation identifier, and storage contains several similarly named files. None of those records establishes which output was selected, transformed, and delivered. More logs would not necessarily close the gap.
Traceability means preserving relationships across those boundaries. This tutorial follows a hypothetical campaign workspace that generates a product visual, resizes it, obtains approval, and delivers it to an export destination. The record shapes are illustrative engineering patterns, not XVAPI API schemas or implementation guarantees. The goal is an explainable lifecycle without indiscriminately retaining sensitive content.
Give the business job a stable identifier that survives retries and worker restarts. Each provider submission receives a separate attempt identifier. Each stored artifact has its own identifier, and each delivery operation has another. A transport request or tracing span may disappear long before the business workflow ends; neither should be the sole job identity.
Carry the tenant boundary through every record and authorization check. An opaque job identifier is not permission to inspect that job. When a worker loads a reference asset or a delivery service resolves an artifact, it must verify the relationship belongs to the authorized tenant, even if the identifier came from another internal service.
A minimal relationship model can be expressed without committing to a particular database:
job -> specification revision
job -> attempts -> provider operations
attempt -> source artifacts
source artifact -> transformations -> derived artifacts
approved artifact -> delivery attempts -> delivery receipts
Do not overwrite an earlier attempt when retrying. Keeping separate records makes duplicate execution visible and allows financial reconciliation even when only one output is ultimately selected. The business job can succeed while another attempt still needs investigation.
Record a versioned specification when work is accepted. Include the requested operation, model selection intent, generation parameters, prompt-template revision, reference-asset identifiers, and relevant policy version. If routing selects a concrete provider or model later, record that decision on the attempt rather than rewriting what the user originally requested.
Store sensitive prompts in a protected content store only when justified by the product's retention policy. Operational events can reference that record instead of copying its contents. A fingerprint can help detect changes, but a hash of a predictable prompt is not anonymization; an attacker may guess candidate values. Keyed fingerprints may reduce that exposure when equality checks are needed.
Distinguish exact replay from explanatory reconstruction. Seeds, parameters, and model names may not reproduce identical output when providers change implementations or do not expose model revisions. Record what was actually known and label unavailable details. Traceability can explain the inputs and decisions without promising deterministic regeneration.
In the campaign workspace, editing the prompt after approval creates a new specification revision. It must not retroactively change the history of the approved image. The interface can show the latest text while the export record still points to the precise revision that produced its source artifact.
Define explicit transitions such as accepted, queued, submitted, reconciling, generated, and failed. Track approval, delivery, and settlement separately when they can progress independently. A single completed flag cannot explain whether generation finished, an editor approved the result, or the destination actually acknowledged receipt.
Write a state change and its outgoing event transactionally, commonly through an outbox. Consumers should tolerate duplicate delivery by using stable event identifiers. An event envelope needs the job, tenant, attempt when applicable, event type, schema version, and timestamps. Avoid embedding raw prompts or signed download URLs in general-purpose event streams.
Ordering deserves explicit treatment. Events from separate workers can arrive late or out of order, and wall clocks can disagree. A per-job sequence or conditional state version helps reject stale transitions. Preserve both observed time and recorded time where useful, but do not pretend timestamps alone establish a globally reliable causal order.
Event history also needs access controls and a correction policy. Prefer appended corrections over silent edits to audit records. However, append-only design does not mean indefinite retention or exemption from deletion requirements. Keep sensitive payloads outside durable event envelopes so they can be removed without destroying the minimal operational relationship history.
Distributed tracing helps investigate latency and failures across admission, queue handling, provider submission, artifact processing, and delivery. Propagate context through controlled queue metadata, and create links for asynchronous work that outlives its original request. The W3C Trace Context recommendation provides a standard foundation for interoperable propagation.
Treat incoming tracing headers as untrusted metadata, not authorization. Validate their format and avoid placing prompts, credentials, or customer names in baggage. When calling an external provider, forward context only where the integration and data-sharing policy permit it. Store the provider's request identifier separately if it is returned.
Sampled traces are not an audit ledger. A trace may be dropped, truncated, or expire before a support case arrives. Persist the small set of business identifiers and state transitions needed for accountability independently of tracing. This adds storage overhead, but avoids coupling customer explanations to an observability sampling decision.
When generation returns an asset, validate its media type, dimensions, size, and integrity before promoting it to a deliverable artifact. Fetch provider-hosted URLs through a constrained retrieval path with destination and redirect checks; otherwise asset ingestion can become a server-side request forgery boundary. Scan or isolate untrusted media according to its format and processing risks.
Record a content digest, storage object version, producing attempt, and validation outcome. Derived files should reference their source artifact and transformation revision. A resized image is a new artifact, not a reason to replace the original record. Content digests identify byte equality; they do not prove who authored an image or whether its generation was authorized.
Approval should bind to an artifact version. If a later retry produces a different image, earlier approval must not automatically transfer to it. In the campaign example, the export service resolves the approved artifact identifier rather than selecting whichever file was most recently written to a folder.
Retention introduces a deliberate limit. Deleting source bytes may prevent future inspection or regeneration, even if lineage metadata remains. Record deletion events and retention reasons, and make that loss of capability visible to authorized operators. Do not describe a metadata-only record as a complete archive of the original media.
An artifact existing in storage does not prove that a customer received it. Record delivery attempts separately, including destination class, artifact version, sanitized response, and acknowledgment semantics. For browser downloads, issuing a signed URL may establish availability without proving a human saved or viewed the file. Use precise status names rather than claiming more than the evidence supports.
For webhook delivery, use authenticated callbacks, replay protection, bounded retries, and a stable delivery identifier that receivers can deduplicate. A lost acknowledgment can cause duplicate delivery even when the receiver processed the first request. RFC 9110 HTTP Semantics is relevant when defining method behavior and deciding which repeats are safe.
Treat signed URLs as credentials: keep them short-lived, exclude them from routine logs, and regenerate them only after authorization. A receipt should reference an artifact, not preserve a reusable access token. Delivery failure should not erase successful generation or cause an automatic new provider submission.
Support should be able to follow a job from accepted specification through attempts, artifacts, approval, and delivery. Default to identifiers and sanitized summaries; reveal sensitive content only through role-based access with an audit trail. The OWASP Logging Cheat Sheet is a useful reference for data exclusions, event quality, and log protection.
Rehearse the wrong-image complaint: locate the delivered artifact, inspect its approval binding, follow its transformation chain, and identify the producing attempt and specification revision. Then repeat with an expired trace and deleted source media. The investigation should state exactly what remains knowable, rather than filling missing evidence with assumptions.
Traceable media jobs do not require saving everything. They require preserving the right relationships, protecting the content behind them, and being precise about what each recorded event actually proves.