Skip to content

Delve 26: Let's Build a Modern ML Microservice Application - Part 12, Streamlit Web UI

Let's Build a Modern ML Microservice Application - Part 12, Streamlit Web UI — DataDelver

"Design is not just what it looks like and feels like. Design is how it works." - Steve Jobs

Hello data delvers! Welcome back to our modern ML microservices series. In part eleven we converted the orchestrator to async and saw just how much of a performance improvement it could provide! That's great for the people calling our API from code... but what about demoing our service to non-technical stakeholders? Right now, the only way to use our application is to carefully construct a JSON payload with dozens of fields and fire off a get request and then inspect a JSON output, not exactly accessible. It's time to change that!

View the Code on GitHub

Streamlit

Whenever I need to demo a capability I've built to stakeholders, Streamlit is my go-to framework. It works by converting a simple Python script into a web UI. It's not the flashiest interface, but for someone who isn't as familiar with front-end frameworks, it's extremely convenient. It also enables us to keep our full application stack in Python which is a huge simplicity win!

With this new UI built, this is what our stack will now look like:

graph TD
    Browser[Browser] --> UI[housing-price-ui - Streamlit]
    UI --> Orchestrator[Orchestrator Service]
    Client[API Client] --> Orchestrator
    subgraph "Orchestrator Service"
        Orchestrator --> PricingService[Pricing Service]
        PricingService --> Provider[MLFlow Model Provider]
    end
    Provider --> ModelServer[ML Model Server]
    MLFlowServer[MLflow Server] -.->|"training / deployment"| ModelServer

And our service lineup grows accordingly:

Service Port Description
housing-price-ui 8501 Streamlit web application for interactive housing price predictions
housing-price-orchestrator 8000 FastAPI REST API that receives prediction requests and orchestrates calls to the model
housing-price-model 8080 MLflow model server serving a trained scikit-learn regression model via MLServer
mlflow-server — MLflow tracking server and model registry for experiment tracking and model versioning

AI for UI

Streamlit UIs for demos are one of my favorite things to automate the creation of via an LLM. As the stakes are low, it's a perfect use case to let an LLM "vibe" a suitable prototype for you to edit. Here's the prompt I used to generate this one (utilizing Qwen3.8-27b as my backend):

Claude

Create a streamlit app that demos the functionality of this service, it should allow selecting a sample from the test set and sending it to the orchestrator for inference. Calls to the orchestrator should be async. Display the prediction along with key model inputs as a result.

Let's see how it did!

A New Workspace Member

Adding the service to our uv workspace is a simple one-liner:

pyproject.toml
members = ["housing-price-model", "housing-price-orchestrator", "housing-price-ui"]

Just like the orchestrator, the UI is a small, well-layered application. Here's the layout:

housing-price-ui/
├── src/
│   ├── config/
│   │   └── settings.py          # Pydantic settings (env-based config)
│   ├── client/
│   │   └── orchestrator_client.py  # Async HTTP client for the orchestrator
│   ├── models/
│   │   └── prediction_models.py    # Pydantic request/response models
│   ├── ui/
│   │   └── app.py               # The Streamlit application
│   └── main.py                  # Entry point
├── samples/
│   └── samples.json             # Sample properties for the UI
├── tests/
│   └── unit/
├── Dockerfile
└── pyproject.toml

The layering mirrors the orchestrator: the UI only knows about a client, the client only knows about models, and config is read from the environment. No layer reaches across another.

Models

To start we need Pydantic models that mirror the orchestrator's request and response schema. Since the orchestrator expects PascalCase field names on the wire (to match the model feature names), we use serialization_alias to keep our Python code using snake_case while speaking the API's language:

housing-price-ui/src/models/prediction_models.py
class PricePredictionRequest(BaseModel):
    """Request model for predicting a single housing price."""

    id: int = Field(ge=1, serialization_alias="Id")
    ms_sub_class: int = Field(ge=20, le=190, serialization_alias="MSSubClass")
    ms_zoning: Literal["A", "C", "FV", "I", "RH", "RL", "RP", "RM"] = Field(
        serialization_alias="MSZoning"
    )
    # ... dozens more fields with the same pattern

Note

Now, you might point out: this is a lot of duplicated schema, and you would be right! In future delves we'll explore publishing the orchestrator models as a shared library that both services import.

Config

Configuration follows the exact same pattern we established in part four: pydantic-settings reads from environment variables with sensible defaults:

housing-price-ui/src/config/settings.py
3
4
5
6
7
class UIConfigSettings(BaseSettings):
    """Configuration settings for the housing price UI application."""

    orchestrator_url: str = "http://localhost:8000"
    """Base URL for the housing price orchestrator API."""

Locally, the UI talks to localhost:8000. In Docker, we'll override ORCHESTRATOR_URL to point at the orchestrator service.

The Client

The client is a thin wrapper over httpx and here we get to put part eleven's async work to use. Since the orchestrator is now async, there's no reason the client shouldn't be either:

housing-price-ui/src/client/orchestrator_client.py
class OrchestratorClient:
    """Asynchronous HTTP client for communicating with the housing price orchestrator."""

    def __init__(self, base_url: str = "http://localhost:8000"):
        self._client = httpx.AsyncClient(base_url=base_url, timeout=30.0)

    async def __aenter__(self) -> "OrchestratorClient":
        """Support use as an async context manager."""
        return self

    async def __aexit__(self, *exc_info) -> None:
        """Close the underlying HTTP client when exiting the context."""
        await self.aclose()

We implemented the async context manager protocol so the client can be used with async with which means the underlying httpx.AsyncClient gets closed deterministically, no matter how the request goes. (Remember from part eleven: forgetting to close your HTTP client is how connection leaks happen.)

housing-price-ui/src/client/orchestrator_client.py
async def predict(self, request: PricePredictionRequest) -> PricePredictionResponse:
    """Send a single prediction request to the orchestrator."""
    response = await self._client.post(
        "/api/v1/price/predict",
        json=request.model_dump(),
    )
    if response.status_code != 200:
        raise Exception(
            f"Prediction failed with status {response.status_code}: {response.text}"
        )
    return PricePredictionResponse.model_validate(response.json())

There's also a predict_batch method that hits the batch endpoint in the same way.

The App

The app itself is where Streamlit shines. Rather than force users to fill in a 60-field form, we ship a small set of five sample properties in a samples.json file, and let the user browse them:

housing-price-ui/src/ui/app.py
def main():
    st.set_page_config(page_title="Housing Price Predictor", layout="wide")
    st.title("Housing Price Prediction")

    # Load samples
    samples = load_samples()
    sample_labels = [s["label"] for s in samples]

    # Sidebar selector
    st.sidebar.header("Select a Property")
    st.sidebar.markdown(
        "Choose a sample property from the test set to predict its price."
    )
    selected_label = st.sidebar.selectbox("Property", sample_labels, index=2)

For the selected property, the app renders a compact "Property Overview" of the most interesting fields: neighborhood, style, quality, living area, bedrooms, garage, each formatted with a collapsible "View All Fields" table for the full record:

housing-price-ui/src/ui/app.py
def format_value(key: str, value) -> str:
    """Format a field value for display."""
    if value is None:
        return "N/A"
    if key in _SUFFIX_SF:
        return f"{value:,} sqft"
    if key in ("overall_qual", "overall_cond"):
        return f"{value}/10"
    return str(value)

And finally, the predict button. There's one subtle thing here worth calling out. Streamlit executes your script in a worker thread, and asyncio.run() refuses to run if there's already a running event loop on that thread, which is a classic pitfall in Streamlit apps. Fortunately, Streamlit 1.66 keeps a persistent, non-running event loop for the script thread, which means asyncio.run() is safe to call on every rerun:

housing-price-ui/src/ui/app.py
async def predict_price(request: PricePredictionRequest) -> PricePredictionResponse:
    """Create a client for this event loop, predict, and clean up."""
    settings = UIConfigSettings()
    async with OrchestratorClient(base_url=settings.orchestrator_url) as client:
        return await client.predict(request)
housing-price-ui/src/ui/app.py
request = build_prediction_request(sample_data, request_id=request_id)

with st.spinner("Predicting price..."):
    # Streamlit's script runner keeps a persistent, non-running event
    # loop for the script thread, so asyncio.run() is safe on rerun.
    result = asyncio.run(predict_price(request))

st.success(f"**Predicted Price:** {format_price(result.predicted_price)}")

Note that we create the client inside the async function, rather than caching it in st.session_state. Since the client is now scoped to a single request via the context manager, and asyncio.run() gives it a fresh event loop each time, there's no need to hold the client across reruns and no risk of a client getting bound to a dead event loop.

Testing

While we could test the streamlit app directly, adding a few helper tests for the validation functions is where the real lift is:

housing-price-ui/tests/unit/test_app.py
1
2
3
4
5
6
7
8
9
class TestValidatePredictionRequest:
    def test_valid_sample_data_returns_none_error(self):
        """Sample data from samples.json should validate without errors."""
        samples = load_samples()
        for sample in samples:
            errors = validate_prediction_request(sample["data"])
            assert errors is None, (
                f"Sample {sample['label']} failed validation: {errors}"
            )

This asserts that every bundled sample actually passes validation, so a future schema change can't silently break the demo data. For the async client, we lean on pytest-asyncio (configured in auto mode so we don't need markers on every test) and pytest-httpx to mock the orchestrator:

housing-price-ui/tests/unit/test_orchestrator_client.py
async def test_predict_success(self, httpx_mock):
    httpx_mock.add_response(
        json={"Id": 1, "PredictedPrice": 250000.0},
    )
    async with OrchestratorClient(base_url="http://orchestrator") as client:
        request = build_test_request()
        result = await client.predict(request)

    assert result.predicted_price == 250000.0

Containerizing the UI

The Dockerfile follows the same multi-stage uv recipe as the orchestrator, with one important twist. Since housing-price-ui is a workspace member, its dependencies live in the root uv.lock not in a lockfile inside the service directory. To build the service while consuming the workspace lockfile, we pass the project root as an additional build context and bind-mount the root lockfile into the build:

housing-price-ui/Dockerfile
# Install the project's dependencies using the lockfile and settings
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock,from=project_root \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --frozen --no-install-project

That from=project_root is the key: it references a second build context we declare in the compose file:

compose.yaml
  housing-price-ui:
    build:
      context: housing-price-ui
      additional_contexts:
        project_root: .
    environment:
      - ORCHESTRATOR_URL=http://housing-price-orchestrator:8000
    ports:
      - "8501:8501"
    depends_on:
      - housing-price-orchestrator

Notice how the ORCHESTRATOR_URL environment variable does the work that the default in UIConfigSettings does locally inside the compose network, the UI reaches the orchestrator by service name. And the default CMD just runs Streamlit:

housing-price-ui/Dockerfile
CMD ["streamlit", "run", "src/main.py", "--server.port", "8501", "--server.address", "0.0.0.0"]

With just up, the whole stack: UI, orchestrator, model, MLflow comes up and the app is available at http://localhost:8501.

Streamlit

Congratulations, you can now demo any models you build! As always, full code available here!

Delve Data

  • Streamlit turns a plain Python script into a web UI, making it ideal for quickly demoing a model's capabilities without leaving Python
  • Low-stakes demo UIs are a great use case for LLM-assisted prototyping, since the generated result is a working starting point you can edit by hand

Related Delves

Delve 25: Let's Build a Modern ML Microservice Application - Part 11, Async · 11 min read

Hello data delvers! After a bit of a hiatus, I wanted to return to our modern ML microservices series. Part ten of...

Delve 23: Let's Build a Modern ML Microservice Application - Part 10, Improving DevX with AI · 17 min read

Greetings data delvers! It has been a while since we last delved into modern ML microservices. In part nine of this...

Delve 19: Let's Build a Modern ML Microservice Application - Part 9, Docker Container Optimization · 12 min read

Greetings data delvers! In part eight of this series we deployed our first multi-service system. In this part, we...

Delve 15: Let's Build a Modern ML Microservice Application - Part 8, The Orchestrator Service · 20 min read

Greetings data delvers! In part seven of this series we finally deployed a model! For this part we'll examine how to...

Delve 13: Let's Build a Modern ML Microservice Application - Part 7, Model Tracking and APIs with MLFlow · 18 min read

Hello data delvers! In part six of this series we containerized our application, making it portable and easy to...

Get New Delves in Your Inbox

No spam, no noise. Just a short note when a new delve goes live.