Deploying and a Cost/Safety Checklist

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 64 of 224

What Changes Between Local Development and a Real Deployment

Every lesson in this capstone so far has run against a local development setup — an API key available as an environment variable, in-memory storage that resets every time the process restarts, no real users other than whoever is testing it. Moving toward an actual deployment means revisiting several of these choices deliberately, and this lesson works through what needs to change, organized as a checklist that draws together practices from across this course rather than introducing substantial new material of its own.

Configuration and Secrets

The API key should never be hardcoded into source code at any point, including during local development, since code has a way of ending up somewhere it wasn't meant to (a public repository, a shared screen) far more easily than an environment variable does.

import os
from openai import AsyncOpenAI

# Never do this:
# async_client = AsyncOpenAI(api_key="sk-...")

# Instead, rely on the OPENAI_API_KEY environment variable (the SDK reads it
# automatically), or read a deployment-specific secret explicitly:
async_client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])

For an actual deployment, this environment variable should come from the hosting platform's own secrets management (rather than a checked-in .env file), and the same principle extends to any other credential the application depends on — a database connection string, for instance, once Lesson 1's in-memory storage is replaced with something persistent.

Replacing In-Memory Storage

Lesson 1 deliberately scoped this capstone to use in-memory storage for document chunks and conversation history, explicitly noting that a real deployment would need something persistent — this is the point where that substitution actually needs to happen.

# In-memory (this capstone's scope): lost on every restart, not shared across
# multiple server instances.
document_store: dict = {}

# A real deployment needs a database (or a dedicated vector database for the
# embeddings specifically) so that data survives restarts and is visible
# consistently across every server instance handling requests.

This substitution matters for two distinct reasons, not just one: data surviving a restart is the more obvious concern, but a deployed application typically runs more than one server instance for reliability and load handling, and an in-memory dictionary in one instance's process is invisible to every other instance — a document uploaded through one instance would simply not be found by a chat request handled by a different instance.

Applying Unit 12's Production-Readiness Practices

Everything Unit 12 covered — error handling, retries, timeouts, rate limiting — applies directly to this capstone's actual deployment, and skipping any of it here reproduces exactly the gaps that unit worked through in the abstract.

from openai import AsyncOpenAI

async_client = AsyncOpenAI(
    max_retries=3,     # Unit 12, Lesson 2
    timeout=30.0,       # Unit 12, Lesson 2
)

Beyond client configuration, the application-level rate limiter from Unit 12, Lesson 3 becomes genuinely necessary once real users are making requests concurrently rather than a single developer testing one request at a time — without it, a burst of simultaneous chat requests across many users could exceed the account's actual rate limit in a way that never surfaced during local development.

Applying Unit 12's Moderation Guidance

A document assistant accepting arbitrary user-uploaded content and arbitrary user questions is exactly the kind of application Unit 12, Lesson 7's moderation guidance was written for — checking both what a user submits and what the assistant generates before it reaches another user.

async def is_content_safe(async_client, text: str) -> bool:
    result = (await async_client.moderations.create(input=text)).results[0]
    return not result.flagged

@app.post("/chat")
async def chat_with_moderation(request: ChatRequest):
    if not await is_content_safe(async_client, request.message):
        raise HTTPException(status_code=400, detail="This message doesn't meet content guidelines.")
    # ... proceed with retrieval and response generation as in Lesson 2

This check is easy to skip during local development, where the only inputs being tested are the developer's own — it becomes necessary the moment the application is reachable by anyone else, exactly the transition this lesson is about.

A Pre-Launch Checklist

Pulling every consideration above (and a few additional ones specific to launching) together into one concrete list to work through before an actual deployment:

  1. Secrets: API keys and any database credentials come from the hosting platform's secrets management, never hardcoded or committed to source control.
  2. Persistence: document storage and conversation history use a real database rather than the in-memory stores this capstone used for clarity during development.
  3. Client configuration: max_retries and timeout are set explicitly (Unit 12, Lesson 2) rather than relying on undocumented defaults.
  4. Rate limiting: an application-level rate limiter (Unit 12, Lesson 3) is in place if concurrent usage could plausibly approach the account's actual rate limit.
  5. Error handling: every endpoint catches upstream API errors and translates them into meaningful HTTP responses (Lesson 2), rather than allowing an unhandled exception to reach the client as a generic failure.
  6. Moderation: user input and, where practical, model output are checked against Unit 12, Lesson 7's moderation guidance before an application is reachable by real users.
  7. Logging: enough is logged to diagnose a production issue after the fact — which requests failed and why — without over-retaining sensitive content, following Unit 12, Lesson 7's data-handling caution.
  8. Cost awareness: at minimum, max_output_tokens is capped to a sensible bound, and the system prompt's shared, static portions are structured to take advantage of prompt caching (Unit 12, Lesson 4) where the request volume would make that meaningful.

A Brief Cost Checklist Beyond What's Already Covered

Unit 12, Lesson 4 covered prompt caching and cost optimization at length; two points specific to this capstone's shape are worth calling out directly before launch. First, retrieval calls an embeddings model on every single chat message to embed the incoming question — this is a small, cheap call individually, but it's worth confirming it isn't being made redundantly (embedding the same repeated question twice within one request, for instance). Second, the system instructions built in Lesson 2 include the retrieved document context as part of the prompt on every turn — following Unit 12, Lesson 4's caching guidance, structuring a prompt with any genuinely static portions (like the base instruction text, separate from the per-turn retrieved context) first would let that static portion benefit from caching, even though the retrieved context itself necessarily changes from turn to turn and can't be cached the same way.

Common Mistakes

Deploying with in-memory storage unchanged, losing all data on every restart and producing inconsistent behavior across multiple server instances handling different requests.

Skipping application-level rate limiting because it was never needed during single-developer local testing, only to discover the account's actual rate limit under real concurrent usage.

Adding moderation and safety checks as an afterthought post-launch, rather than as part of the pre-launch checklist before an application is reachable by anyone outside development.

Treating Unit 12's production-readiness practices as optional polish rather than integral to an actual deployment, when skipping them reproduces the exact gaps that unit was written to close.

Best Practices

Work through a concrete pre-launch checklist before deploying, rather than assuming a locally-working application is automatically ready for real users.

Replace in-memory storage with real persistence before any deployment involving more than one server instance or requiring data to survive a restart.

Apply Unit 12's retry, timeout, rate-limiting, and moderation practices as a baseline for any deployed application, not as optional additions reserved for large-scale systems.

Revisit cost structure specifically for this application's shape, checking for redundant embedding calls and structuring prompts to take advantage of caching where request volume justifies it.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Deploying and a Cost/Safety Checklist and get answers drawn from it.

Signed-in readers only.