React with a Python and Java Backend: When Two Backend Languages Make Sense
By WebNest Studio Engineering Team · Published · Updated · 8 min read
A React frontend backed by both a Java service and a Python service is a common architecture in teams that combine transactional business software with data science. It is also a common source of avoidable cost when it is chosen for the wrong reasons. This guide covers when the combination earns its keep, how to divide responsibilities, and how to connect the pieces safely, with a small working example.
Start with one backend unless you have a reason for two
Two backend languages mean two build pipelines, two sets of dependencies to patch, two runtimes to monitor, and developers who need to read both. That overhead is worth paying only when each language gives your project something the other cannot provide cheaply.
For most business applications, such as a customer portal, an internal tool, a booking system or a CRM, one backend is enough:
- Java with Spring Boot suits large, long-lived codebases with complex transactional rules, several developers working in parallel, and strict typing as a guard rail.
- Python with FastAPI suits smaller teams that want to move quickly, and applications whose core is data processing or machine learning.
Both can call a hosted large language model API, so "we want AI features" is not, on its own, a reason to run both.
When a second backend language pays off
The combination makes sense when the work genuinely divides:
- Your core business logic already runs on the JVM. Orders, billing, inventory and permissions live in an existing Spring Boot application, and rewriting them is not an option.
- You need Python's data and machine-learning ecosystem. Training and serving models with libraries such as scikit-learn, PyTorch or pandas, and the data scientists who use them, work in Python.
- The two parts change at different speeds. A risk or recommendation model is retrained and redeployed often; the order workflow changes rarely and must stay stable.
- Different teams own them. A clear service boundary lets each team release without coordinating every change with the other.
If two or more of these are true, a split is worth considering. If none are, keep one backend.
A sensible division of responsibilities
A pattern that works well in practice:
- React talks to one backend only: the Java application, or an API gateway in front of it. The browser should not need to know that a Python service exists. That keeps authentication, CORS and error handling in one place.
- Spring Boot owns the system of record: users, permissions, orders, payments and anything that needs database transactions. It validates every request and decides what the user is allowed to do.
- FastAPI provides focused capabilities behind the Java service: scoring, recommendations, document processing or forecasting. It receives only the data it needs, returns a result, and does not write to the core database.
The most important rule is one owner for each piece of data. If both services write to the same tables, every schema change needs both teams and both languages, and most of the benefit of separating them is lost.
Worked example: scoring cash-on-delivery orders
Suppose an online store wants to ask for prepayment on cash-on-delivery orders that look likely to be refused at the door. The order flow lives in Spring Boot. The data team has a model, built in Python, that estimates the chance of refusal from an order's details.
The Python service
The FastAPI service exposes a single endpoint with a typed, validated contract. Amounts are integers in paise to avoid floating-point rounding.
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class ScoreRequest(BaseModel):
amount: int = Field(gt=0, description="Order total in paise")
items: int = Field(ge=1)
pincode: str = Field(pattern=r"^\d{6}$")
refusals: int = Field(ge=0, description="Earlier COD orders this customer refused")
class ScoreResponse(BaseModel):
risk: float = Field(ge=0, le=1)
model: str
def predict_refusal_risk(order: ScoreRequest) -> float:
# Stand-in for the trained model so the example runs on its own.
risk = 0.05 + 0.15 * min(order.refusals, 3)
if order.amount > 500_000: # above Rs 5,000
risk += 0.10
return min(risk, 1.0)
@app.post("/score", response_model=ScoreResponse)
def score(order: ScoreRequest) -> ScoreResponse:
return ScoreResponse(risk=predict_refusal_risk(order), model="cod-risk-v3")
Pydantic rejects malformed input with a 422 response before your code runs, and FastAPI publishes the contract as an OpenAPI document at /openapi.json automatically.
The Java client
The Spring Boot side calls the service with strict timeouts and treats any failure as "no score", never as an error the customer sees.
public record ScoreRequest(long amount, int items, String pincode, int refusals) {}
public record ScoreResponse(double risk, String model) {}
@Component
public class RiskClient {
private static final Logger log = LoggerFactory.getLogger(RiskClient.class);
private final RestClient restClient;
public RiskClient(@Value("${risk.base-url}") String baseUrl) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(1));
factory.setReadTimeout(Duration.ofSeconds(2));
this.restClient = RestClient.builder().baseUrl(baseUrl).requestFactory(factory).build();
}
public Optional<ScoreResponse> score(ScoreRequest request) {
try {
return Optional.ofNullable(restClient.post()
.uri("/score")
.contentType(MediaType.APPLICATION_JSON)
.body(request)
.retrieve()
.body(ScoreResponse.class));
} catch (RestClientException e) {
log.warn("Risk service unavailable; using the fallback rule", e);
return Optional.empty();
}
}
}
The order service makes the business decision, with a simple rule to fall back on:
boolean requirePrepayment = riskClient.score(request)
.map(result -> result.risk() >= 0.4)
.orElseGet(() -> request.amount() > 1_000_000); // no score: prepay above Rs 10,000
Three details matter more than the code itself:
- The decision stays in Java. Python returns a number; the order service owns the rule that turns it into "ask for prepayment". Changing the threshold does not require the data team.
- Failure has a defined behaviour. If the model is slow or down, checkout still works using a conservative rule. Without timeouts, a stuck Python service would hold Java request threads until checkout itself stopped responding.
- Store the model version with the order. When someone later asks why an order needed prepayment,
cod-risk-v3tells you which model made the call.
The thresholds above are illustrative; a real system would set them from the model's measured accuracy and the business's tolerance for refused parcels.
Contracts, not shared code
The two services share a contract, not a library. Treat the OpenAPI document as the source of truth: generate or check the Java request and response types against it, and add a contract test to both pipelines so a renamed field fails a build instead of failing in production. Change the contract by adding optional fields first and removing old ones only after both sides have been deployed.
Security between the services
The user's token is checked once, by the Java application. The Python service should not be reachable from the internet at all; run it on a private network and authenticate calls from the Java service with a service credential or mutual TLS. Send it only the fields the model needs. In the example above that excludes the customer's name, phone number and address.
Synchronous calls or a message queue?
Use a synchronous HTTP call, as above, when a user is waiting for the answer, and keep it fast and bounded by timeouts. Use a message broker such as RabbitMQ or Kafka for work that can finish later: refreshing recommendations, processing uploaded documents or generating reports. The Java service publishes an event, the Python service consumes it and publishes a result, and neither waits for the other.
Running two stacks
- Package both services as containers and give each its own build and deployment pipeline.
- Expose health endpoints on both so the platform can restart an unhealthy instance and stop routing traffic to it.
- Pass a correlation ID, such as the W3C
traceparentheader that OpenTelemetry uses, from React through Java to Python, so one customer's request can be followed across all three logs. - Pin dependency versions in both ecosystems and schedule upgrades for both. Two languages means two sets of security advisories to follow.
Checklist before you commit
- Can you name the capability that requires the second language?
- Does each table have exactly one owning service?
- Does the browser talk to one backend only?
- Does every cross-service call have a timeout and a fallback?
- Is the contract versioned and tested in both pipelines?
- Do you have people who can debug and maintain both stacks?
If any answer is no, fix that first, or stay with one backend until you need the second.
Frequently asked questions
Can React call the FastAPI service directly?
It can, but then authentication, CORS, rate limiting and error handling have to be built and kept consistent in two places. Routing through the Java application or a gateway keeps them in one.
Should the services use gRPC instead of REST?
gRPC is efficient for high-volume internal calls and gives you a strict schema. REST with JSON is easier to inspect and debug and is enough for most business workloads. Start with REST and move a specific call to gRPC if measurements show it is the bottleneck.
Can Spring Boot call machine-learning models without Python?
Sometimes. Hosted model APIs can be called from Java, and some trained models can be exported to formats that run on the JVM. If your data team works in Python and retrains often, a Python service is usually simpler to operate.
Further reading on this site: calling APIs with RestClient, an introduction to FastAPI, retries, rate limits and circuit breakers in Spring Boot and connecting React to an API. If you are weighing this architecture for your own product, our software development team can review the plan with you.