FedMed-AI: Building a Federated Medical Risk Prediction System with Flower, FastAPI, and Spring Boot
A developer’s walkthrough of FedMed-AI, a medical risk prediction system that combines machine learning with federated learning. Explore the architecture, synchronous FedAvg training, Spring Boot orchestration, FastAPI inference, and the engineering decisions behind the project.
FedMed-AI: Building a Federated Medical Risk Prediction System with Flower, FastAPI, and Spring Boot
Introduction
Healthcare data is valuable for building predictive models, but it is also sensitive. A hospital may have enough patient records to train a useful model, yet sharing those records with another organization can introduce privacy, governance, and operational concerns.
That problem led me to build FedMed-AI, a medical risk prediction system that explores how multiple simulated healthcare clients can collaboratively train a machine learning model without sending their raw training data to a central server.
The project combines a web application, a backend service, and a separate machine learning service. It supports prediction workflows for five disease categories:
- Heart disease
- Diabetes
- Chronic kidney disease
- Liver disease
- Stroke
The goal was not to build a production clinical decision system. It was to understand how federated learning could fit into a practical software architecture—and what engineering work is required beyond training a model.
In this article, I’ll walk through the architecture, implementation choices, challenges, and lessons from building FedMed-AI.
Why I built it
A conventional machine learning workflow often centralizes training data:
- Collect records from different sources.
- Combine them in one dataset.
- Train a model.
- Deploy the model for inference.
For healthcare use cases, centralizing records may not be feasible. Federated learning offers another approach: participating clients train locally and send model updates to a coordinator for aggregation.
This changes the data flow, but it does not remove every privacy or security concern. Model updates can still leak information, and federated learning alone is not a guarantee of privacy.
I wanted to explore the complete engineering workflow around this idea:
- How should the application manage users and prediction requests?
- How should the backend communicate with the ML service?
- How can training run without blocking a web request?
- How should the application track training progress?
- How can multiple simulated clients participate in a shared training process?
These questions shaped the project as much as the machine learning component did.
System architecture
FedMed-AI uses a layered architecture. The React frontend communicates with a Spring Boot backend, while the backend integrates with a Python FastAPI service for machine learning operations.
The ML service uses Scikit-learn for model training and inference, and Flower coordinates federated learning between simulated clients using FedAvg.
Architecture diagram
flowchart TD U[User / Admin] --> UI[React Frontend] UI --> NG[Nginx] NG --> API[Spring Boot REST API]
API --> SEC[Spring Security] SEC --> APP[Application Services]
APP --> DB[(PostgreSQL)] APP -->|Prediction request| ML[FastAPI ML Service] APP -->|Start training job| JOB[Background Training Workflow]
JOB -->|POST /ml/train/all| ML JOB --> STATUS[Job Status and Training Logs] STATUS --> DB
ML --> SK[Scikit-learn Models] ML --> FL[Flower Coordinator] FL --> C1[Simulated Client 1] FL --> C2[Simulated Client 2] FL --> C3[Simulated Client 3]
C1 -->|Local model update| FL C2 -->|Local model update| FL C3 -->|Local model update| FLThe architecture separates application responsibilities from model operations.
React frontend
The frontend provides the user interface for application workflows. It communicates with the backend through REST APIs rather than directly accessing the database or ML service.
This keeps authentication, authorization, and application rules in the backend.
Spring Boot backend
Spring Boot is responsible for the application layer:
- REST API endpoints
- Authentication and authorization
- Business logic
- Training-job orchestration
- Persistence of job status and training information
The backend acts as the integration point between the user interface, PostgreSQL, and the Python ML service.
PostgreSQL
PostgreSQL stores application data, including model-training information and job status. Flyway manages versioned database schema migrations.
FastAPI ML service
FastAPI exposes endpoints for ML inference and training. It handles feature preprocessing and communicates with the machine learning components.
Keeping the ML service separate allows Python-based model code to evolve independently of the Java application layer.
Flower and simulated clients
Flower provides the federated learning framework. The project uses simulated clients to represent separate healthcare participants.
Each client trains locally using its own data partition and returns model updates to the coordinator. The coordinator aggregates the updates using FedAvg.
The project uses simulated clients—not real hospitals connected to a production federation.
Technologies and why I selected them
Technology | Role in the project |
|---|---|
React | Frontend and user interaction |
Java and Spring Boot | REST APIs, application logic, and orchestration |
Spring Security | Authentication and authorization |
PostgreSQL | Persistent application and training data |
Flyway | Version-controlled database migrations |
Python and FastAPI | ML inference and training APIs |
Scikit-learn | Machine learning models and preprocessing |
Flower | Federated learning coordination |
FedAvg | Aggregation of client model updates |
Docker | Containerized application components |
Nginx | Frontend serving and API reverse proxy |
I chose Spring Boot for the main application because it provides a structured way to implement REST APIs, security, persistence, and background workflows. Python was a natural fit for the ML component because of its machine learning ecosystem.
The two services communicate through HTTP APIs, which keeps their responsibilities separate without requiring the entire application to be written in one language.
Federated learning with synchronous FedAvg
One of the central concepts in FedMed-AI is the difference between local training and global aggregation.
In a typical federated learning round:
- The coordinator provides the current global model to participating clients.
- Each client trains locally using its own dataset.
- Clients return model updates.
- The coordinator aggregates the updates.
- The resulting global model is used for the next round.
FedMed-AI uses synchronous, round-based federated learning with Flower and FedAvg.
The standard FedAvg aggregation is a weighted average of client model parameters. In simplified form:
[
w_{t+1} = \sum_{k=1}^{K}
\frac{n_k}{\sum_{j=1}^{K} n_j}w_{t+1}^{(k)}
]
Where:
- (w_{t+1}) is the updated global model.
- (w_{t+1}^{(k)}) is the model update from client (k).
- (n_k) is the number of training examples used by client (k).
- (K) is the number of participating clients.
The weighting means that clients with more training examples can contribute proportionally more to the aggregate.
Why synchronous training?
Synchronous FedAvg provides a clear round-based process. It is easier to reason about and debug in a controlled simulation.
It also has a trade-off: slower clients can delay a round. Asynchronous federated learning can accept updates as they arrive, but then the system must handle updates trained from older global model versions.
For this project, synchronous FedAvg was a suitable baseline. Asynchronous federated learning remains a possible future direction rather than a feature I claim to have implemented.
Prediction workflow
The prediction flow separates the application API from model inference.
At a high level:
- A user submits patient features through the React interface.
- The request reaches a Spring Boot REST endpoint.
- The backend applies application-level checks and forwards the relevant features to FastAPI.
- FastAPI performs the required preprocessing and invokes the appropriate Scikit-learn model.
- The ML service returns a prediction response.
- Spring Boot returns the result to the frontend.
The project uses Logistic Regression for classification. Its
predict_proba method can provide estimated class probabilities, but these probabilities are not automatically calibrated and should not be interpreted as a clinical diagnosis.Simplified inference example
The following illustrates the general shape of a Scikit-learn inference call. It is a simplified example, not a verbatim extract from the project:
import numpy as np
def predict_risk(model, features): input_data = np.asarray(features).reshape(1, -1)
predicted_class = model.predict(input_data)[0] probabilities = model.predict_proba(input_data)[0]
return { "predicted_class": int(predicted_class), "class_probabilities": probabilities.tolist() }In a real deployment, the input schema, feature ordering, preprocessing pipeline, and model version must remain consistent between training and inference. A model should not receive a feature vector simply because its length looks correct.
Making model training an asynchronous application workflow
Model training can take longer than a typical REST request. Running the entire workflow inside a request-response cycle would make the API harder to use and could lead to timeouts.
I implemented a background training workflow in the Spring Boot application.
The flow is:
- An administrator requests model training.
- Spring Boot creates a job identifier.
- The job begins in a
PENDINGstate.
- Background execution invokes the FastAPI training endpoint.
- The job status changes as training progresses.
- The frontend polls the backend for the latest status.
The job states include:
PENDING → RUNNING → COMPLETED ↘ FAILEDThe API can return an HTTP
202 Accepted response with a job ID while training continues.A simplified response might look like this:
{ "jobId": "generated-job-id", "status": "PENDING"}The frontend can then query an endpoint such as:
GET /api/jobs/{jobId}This is an important distinction in the project: the training workflow is asynchronous at the application level, while the federated learning process uses synchronous FedAvg rounds. These are separate design decisions.
Engineering challenges and what I learned
1. Separating application logic from ML logic
The backend and ML service use different languages and frameworks. Keeping their responsibilities clear was important.
Spring Boot manages application workflows, while FastAPI handles model-related operations. The boundary is an HTTP API rather than direct access to the Python process.
This separation makes the components easier to develop independently, but it also means API contracts matter. Feature names, data types, expected response fields, and error handling must be consistent.
2. Making long-running training observable
A training request is not complete just because the API successfully starts it.
The user needs to know whether the job is pending, running, completed, or failed. I used a job ID and persisted status information so the frontend can check progress without keeping the original HTTP request open.
This pattern also makes failures easier to inspect than a single long-running request with no status endpoint.
3. Managing database schema changes
As the application evolved, its database schema also changed. Manually applying schema changes can lead to inconsistent environments.
Flyway provides versioned SQL migrations. Each migration represents a change to the schema, and Flyway records which migrations have been applied.
This separates schema evolution from application startup behavior and makes database changes more reproducible.
4. Keeping preprocessing consistent
A machine learning model depends on the exact feature representation used during training.
If training expects one feature order but inference sends another, the application may return a result that is technically valid but semantically wrong. This is especially important when different disease models use different feature sets.
The engineering lesson is to treat preprocessing and feature mapping as part of the model interface—not as incidental code around it.
5. Understanding what federated learning does not solve
Federated learning avoids centralizing raw training data in the intended workflow, but it does not automatically provide complete privacy.
Model updates may still reveal information. A more mature system would need to evaluate additional controls such as secure aggregation, differential privacy, access restrictions, and auditability.
I consider these important future improvements rather than features that should be claimed as already implemented.
Security, scalability, performance, and deployment
Security
The application uses Spring Security for authentication and authorization. The architecture places the backend between the frontend and the ML service, so the browser does not need direct access to internal model endpoints.
For a production healthcare environment, additional work would be required, including:
- Strict authorization for training and administrative operations
- TLS for service-to-service communication
- Secret management outside source code and container images
- Input validation and schema enforcement
- Audit trails for sensitive operations
- A documented data-retention policy
- A formal privacy and security review
The project should not be treated as a certified clinical system or as proof of regulatory compliance.
Scalability
Separating the Java application and Python ML service creates room to scale them independently.
For example, the web API may need more instances during periods of user activity, while ML inference or training may need different compute resources. However, independent scaling also introduces operational responsibilities: service discovery, network configuration, resource limits, retries, and observability.
The current project is a functional architecture and learning environment, not a claim of large-scale production capacity.
Performance
The training workflow avoids holding a normal API request open for the entire duration of training. Job status polling gives the frontend a way to observe progress.
Further performance work could include:
- Measuring inference latency and training duration
- Profiling preprocessing and model execution
- Reducing unnecessary polling
- Introducing a durable queue for training requests
- Defining limits on concurrent training jobs
- Monitoring memory and CPU use in each service
I have not included performance figures because they should come from repeatable measurements rather than estimates.
Deployment
The project uses Docker to package its components, and Nginx serves the React application while reverse-proxying API requests to Spring Boot.
The deployment architecture keeps the frontend, backend, database, and ML service as distinct components. This helps make local development and environment configuration more consistent.
I have not deployed FedMed-AI on AWS, so I do not describe the current system as AWS-hosted.
How AWS could support a future deployment
AWS offers services that could support a more production-oriented version of FedMed-AI. These are possible future integrations, not components currently used by the project.
Potential AWS service | Possible use |
|---|---|
Amazon ECS or Amazon EKS | Run containerized Spring Boot and FastAPI services |
Amazon RDS for PostgreSQL | Managed relational database |
Amazon S3 | Store versioned model artifacts and training datasets where appropriate |
AWS Secrets Manager | Store database credentials and service secrets |
Amazon CloudWatch | Collect logs, metrics, and operational alerts |
Application Load Balancer | Route traffic to application services |
Amazon SQS | Queue training jobs for durable processing |
For example, a durable queue could decouple training requests from the backend. Spring Boot could submit a job, a worker could process it, and the application could persist status transitions.
That approach would be worth considering if the project needed stronger job durability or controlled concurrency. It would also introduce additional design questions around retries, duplicate requests, idempotency, and failure recovery.
For a healthcare-oriented system, I would also evaluate the security, data residency, privacy, and compliance requirements before deciding which AWS services and configurations are appropriate.
Lessons learned and future improvements
Building FedMed-AI taught me that a machine learning application is much more than a model and an endpoint.
The application needs a clear contract between the frontend, backend, and ML service. Training needs lifecycle management. Database changes need a migration strategy. Model inputs need strict preprocessing rules. And a federated learning design needs to be explicit about what it protects—and what it does not.
The next improvements I would prioritize are:
- Model evaluation: Add reproducible evaluation across centralized and federated baselines, using appropriate metrics for each disease dataset.
- Feature contracts: Define and validate disease-specific feature schemas shared by training and inference.
- Training reliability: Add durable job execution, bounded concurrency, retry policies, and idempotency.
- Federated learning experiments: Compare synchronous FedAvg with approaches such as FedProx for non-IID client data.
- Privacy evaluation: Investigate secure aggregation and differential privacy, including their utility and performance trade-offs.
- Observability: Track inference latency, training duration, job failures, and service health.
- Deployment automation: Introduce a repeatable CI/CD process and evaluate AWS deployment options.
These improvements would help move the project from a functional federated learning prototype toward a more robust experimental platform.
Conclusion
FedMed-AI gave me an opportunity to work across backend engineering, machine learning, API design, and distributed training.
The most valuable part was learning how the pieces fit together: React provides the user interface, Spring Boot manages application workflows, FastAPI exposes ML operations, and Flower coordinates local model training through synchronous FedAvg.
The project also reinforced an important point: federated learning changes where training happens, but it does not eliminate the need for careful engineering. Reliable APIs, consistent preprocessing, secure service boundaries, observable jobs, and honest model evaluation are still essential.
For developers exploring federated learning, I found it useful to start with a small, controlled simulation and build the surrounding application architecture deliberately. That makes it easier to understand not only how the model is trained, but how a real software system would manage the process.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article