# One K-Means model, two apps: serving it from FastAPI on EC2

By Sangam Gupta (ML engineer and data scientist), 2026-11-23. Canonical: https://www.sangamgupta.in/writing/one-kmeans-model-two-apps

> My customer segmentation model answers a Streamlit web app and an Android app from one small FastAPI service on AWS EC2. Here's what the service does, and what it doesn't do yet.

In an [earlier post](https://www.sangamgupta.in/writing/why-i-picked-the-clustering-model-with-the-lower-score) I explained why my customer segmentation project uses K-Means with three clusters. This one is about what came after the notebook: getting that model somewhere two different apps could use it.

The project has two clients, a Streamlit web app and a native Android app (the Android app was built with AI help). Neither of them runs the model. Both send a customer's recency, frequency and monetary value to one FastAPI service on AWS EC2 and get a segment back. That means both apps give the same answer for the same customer, and a refitted model only has to be deployed in one place.

## Three files out of the notebook

The last cells of the notebook fit the final model, `KMeans(n_clusters=3, random_state=42, n_init=10)` on the scaled RFM features, and save three files with `joblib`:

- `scaler.joblib`, the `StandardScaler` fitted on the training customers,
- `kmeans_model.joblib`, the model itself,
- `segment_names.joblib`, a small dictionary from cluster number to name.

The scaler has to travel with the model. K-Means works on distances in the scaled space, so a new customer must be scaled with the training data's means and standard deviations. Scaling a single customer on its own, or not at all, would give distances the model never saw.

The names need a file of their own because K-Means only returns 0, 1 or 2, and those numbers mean nothing by themselves. The names come from each cluster's average RFM values: 0 is High-Value / Loyal, 1 is Inactive / Low-Value and 2 is Regular / Mid-Value. Which group gets which number comes from the fit, so the mapping is saved next to the model it describes instead of being typed into each client.

The notebook's last cell loads all three files back and scores a test customer: 20 days since the last purchase, 18 purchases, 140,000 spent. It comes back as cluster 0, High-Value / Loyal.

## The service

The FastAPI app loads the three files once at startup and has two routes: `GET /`, which just says the API is running, and `POST /predict`:

```python
@app.post("/predict")
def predict_customer(data: CustomerData):
    customer_data = [[data.recency, data.frequency, data.monetary]]
    scaled_data = scaler.transform(customer_data)
    cluster = kmeans_model.predict(scaled_data)[0]
    segment = segment_names[cluster]
    return {"cluster": int(cluster), "segment": segment}
```

`CustomerData` is a Pydantic model with three floats, so a request with a missing field or a value that isn't a number is rejected with a validation error before it reaches the model. The `int(cluster)` matters too: `predict` returns a NumPy integer, and converting it to a Python `int` lets FastAPI turn it into JSON. I worked out the API's shape with an AI assistant's help; the model, this service and the deployment are my part.

FastAPI also generates Swagger docs at `/docs`, which is where I tested the endpoint by hand.

## Putting it on EC2

The deployment steps, as I listed them in the README:

1. Launch an Ubuntu EC2 instance and open port 8000 in its security group.
2. SSH in, clone the repository, create a virtual environment and install the requirements.
3. Run the app with Uvicorn on `0.0.0.0:8000` and check the Swagger page.
4. Register it as a systemd service and enable it with `systemctl enable`, so it starts when the server boots instead of living in my SSH session.

One detail from the code: `main.py` loads the model files from a relative `models` folder, so the service has to start from the repository root. Starting it from anywhere else fails at the first `joblib.load`.

## What the clients send

The Streamlit app has three number inputs with limits (recency 0 to 1,000 days, frequency 1 to 1,000 purchases, monetary up to 10,000,000), sends them as JSON to `/predict` and shows the cluster, the segment and a suggested action for that segment. The Android app sends the same JSON through Retrofit to the same address. Neither client knows anything about scaling or cluster numbers.

## What it doesn't do yet

The README is clear that this is a learning deployment, and reading the code again, these are the gaps:

- **Plain HTTP on a public IP and port 8000.** The Android app has to allow cleartext traffic to reach it. HTTPS, a custom domain, authentication and rate limiting are listed as future work, not done.
- **The address is hard-coded in both clients.** If the server's IP changes, the web app needs a code change and the Android app a new release. A stable Elastic IP is on the README's hardening list.
- **Validation lives in the clients.** The Streamlit form won't accept a negative recency, but the API's schema is three plain floats, so a direct request with `"recency": -5` still gets a segment. The rules belong in the schema, where every client gets them.
- **The response schema isn't used.** `schemas.py` defines a `PredictionResponse` model, but the route doesn't declare it, so the Swagger page can't show what a response looks like.
- **Feature order is an unwritten contract.** The service passes a plain list in the order recency, frequency, monetary. The scaler was fitted on a DataFrame with column names, which is why scikit-learn warns that "X does not have valid feature names" when the notebook scores its test customer. The order matches, so the answer is right, but nothing checks it.

## What I took from it

The model is the smallest part of this. Most of what I had to decide was the contract around it: which files travel together, what a request must contain, where the rules are enforced and how the clients find the server. A notebook hides all of that, because everything sits in one kernel's memory. A deployment makes every one of those decisions visible.

You can try the segments on the case study at [sangamgupta.in/work/customer-intelligence](https://www.sangamgupta.in/work/customer-intelligence), and the notebook, API and both clients are on [GitHub](https://github.com/TheSangamX/customer-intelligence-segmentation).
