From AI prototype to production without freezes
An AI demo that runs on a laptop often stalls in production. These are the patterns that kept the platform fast and stable as the catalog grew.
Why AI prototypes break in production
In the proof-of-concept the container loaded the model, generated embeddings and built the index at startup. Fine for a few hundred images; with a large catalog it caused memory spikes, slow cold starts and health checks that failed before the API was ready, so deploys were rolled back.
Pre-build the index, don't rebuild on startup
Do the heavy work before deployment, not during it. Embeddings are precomputed and the index built in a separate step, then baked into the image or loaded from storage. At runtime the service loads a ready index and responds in seconds.
Serve behind a production server with health checks
Gunicorn with multiple workers replaces the development server, plus lightweight health and readiness endpoints. Health responds immediately so the platform knows the container is alive; readiness flips only once the index is loaded. That distinction removes most failed deploys.
Separate batch work from live serving
Crawling, image downloading, embedding generation and index refresh run as scheduled batch jobs, separate from the API that answers shoppers. The live path stays light and predictable; the heavy path scales independently.
Key decision: prebuilt index and worker count
Two settings make or break startup: never build the index live, and size the workers to the index that sits in memory.
Build the index when the container starts?
- Yes (avoid)slow cold starts, memory spikes, failing health checks
- No (do this)load a prebuilt index from the image or storage; rebuild on a schedule as a separate batch job
How many Gunicorn workers?
Start from (CPU cores × 2) + 1, but each worker loads its own copy of the index into memory:
- Small indexworkers = cores × 2 + 1
- Large index (memory-heavy)fewer workers plus threads, or one worker with a shared cache
Always load-test before fixing the number.
More technical detail
# gunicorn.conf.py
import multiprocessing, os
bind = "0.0.0.0:8000"
workers = int(os.getenv("WEB_CONCURRENCY", multiprocessing.cpu_count()*2 + 1))
threads = int(os.getenv("GUNICORN_THREADS", "2"))
timeout = 180 # AI workloads need a generous timeout
preload_app = False # each worker loads its own index
# readiness flips only once the index is loaded
@app.route("/ready")
def ready():
return ("ready", 200) if INDEX_LOADED else ("starting", 503)