“If I receive create requests from another system and store the resources in a data lake, would switching to Java be more efficient?” I compared Java and Python for this scenario, then asked a follow-up: if FastAPI can also wait asynchronously for the network, why assume a large performance difference in advance?
First, give “received” and “stored” observable outcomes. An outpatient system sends data for a fictional patient named Lin. One milestone is that the patient record has been saved, another that the outpatient client receives a success response, and a third that an analyst reopens the lake table and finds Lin. In this local experiment, the two implementations’ median resource commit times were about 8–9 ms, and reading the record back from the lake took about 39–41 ms from the start. These milestones deserve separate measurements even if you ultimately choose only one language.
What changes when the same patient data goes to HAPI FHIR or FastAPI?
The outpatient system sends POST /Patient to register Lin. The body follows the FHIR R4 healthcare exchange standard’s Patient structure and includes teaching record number P42. The experiment submits the same request structure to Java and Python services. Follow either column downward, then see what the other does at the same step.
flowchart TD
C["门诊系统提交 Lin 的患者资料<br/>POST /Patient"]
subgraph J["Java · HAPI FHIR Plain Server"]
J1["Jetty 接收请求<br/>HAPI 解析成 Patient,交给 @Create 方法"]
J2["用 JDBC 写入患者档案和变更记录<br/>① 显式提交 SQLite 事务"]
J3["方法返回 MethodOutcome<br/>HAPI 据此生成创建响应"]
J1 --> J2 --> J3
end
subgraph P["Python · FastAPI"]
P1["Uvicorn 接收请求,FastAPI 找到函数<br/>函数调用 Patient.parse_obj 解析资料"]
P2["用 sqlite3 写入患者档案和变更记录<br/>① 正常退出事务块时提交"]
P3["函数构造创建响应<br/>写入状态码、患者资料和响应头"]
P1 --> P2 --> P3
end
C --> J1
C --> P1
J3 --> R["② 客户端收到 201 和变更序号"]
P3 --> R
R --> W["同一段 Python 入湖逻辑<br/>按序号读出变更,按患者 ID 写入 Delta 表"]
W --> V["③ 重新打开湖表,核对患者 ID 和姓氏 Lin"]
Both columns first check the family name, returning HTTP 400 if it is missing. After validation, the service assigns a patient ID and writes the record and change event in one transaction so they take effect together. The diagram’s ① commit, ② response received, ③ lake row readable correspond to the three timing columns below.
Each experiment uses a fresh SQLite database and Delta table. The bottom of the diagram is shared because both rounds use the same lake ingestion code for their respective events. Compare intake implementations by measuring from request send to ① and to ②. To find how much longer the outpatient system must wait after success before Lin appears in the lake, subtract time ② from time ③ for the same request.12
What layers does the Python request pass through?
Uvicorn accepts HTTP connections. FastAPI matches the method and path to a function. fhir.resources supplies the model that understands patient fields. The relevant operations are below, omitting error responses and timing instrumentation. Database queries bind parameters to ? placeholders. The transaction commits on leaving the block. Patient records and pending events survive a service restart.3
patient = Patient.parse_obj(payload)
if not patient.name or not patient.name[0].family:
raise HTTPException(400, "Expected Patient with a family name")
patient.id = uuid4().hex
body = patient.json()
with database() as db:
db.execute("INSERT INTO resources VALUES ('Patient',?,1,?)", (patient.id, body))
seq = append_change(db, "Patient", patient.id, body)
append_change inserts a row into the change table and returns its sequence number. Even if the following lake write fails, operations staff have a durable event to retry. The response includes Location for the new resource and X-Change as this experiment’s reconciliation number. One ID can be followed to the database resource and its lake row.
With HAPI in Java, what does the framework do?
HAPI FHIR is a Java FHIR library. This example uses its Plain Server, which lets developers control resource storage. Jetty receives HTTP requests. HAPI’s RestfulServer maps POST /Patient to the registered patient handler, parses the body into an R4 Patient object, and calls the method annotated @Create. This is where a hospital can map records to its existing database.4
@Create
public MethodOutcome create(@ResourceParam Patient patient, HttpServletResponse response) throws SQLException {
if (!patient.hasName() || !patient.getNameFirstRep().hasFamily()) {
throw new InvalidRequestException("Expected a family name");
}
String id = UUID.randomUUID().toString().replace("-", "");
patient.setId(id);
String body = R4.newJsonParser().encodeResourceToString(patient);
try (var db = DriverManager.getConnection(DB)) {
db.setAutoCommit(false);
try (var save = db.prepareStatement("INSERT INTO resources VALUES ('Patient',?,1,?)");
var change = db.prepareStatement("INSERT INTO changes(kind,id,body) VALUES ('Patient',?,?)");
var statement = db.createStatement()) {
save.setString(1, id); save.setString(2, body); save.executeUpdate();
change.setString(1, id); change.setString(2, body); change.executeUpdate();
try (var key = statement.executeQuery("SELECT last_insert_rowid()")) {
key.next();
response.setHeader("X-Change", key.getString(1));
}
db.commit();
var now = Instant.now();
response.setHeader("X-Commit-Ns",
Long.toString(now.getEpochSecond() * 1_000_000_000L + now.getNano()));
} catch (SQLException error) {
db.rollback(); throw error;
}
}
var result = new MethodOutcome();
result.setCreated(true);
result.setId(new IdType("Patient", id, "1"));
result.setResource(patient);
return result;
}
The running version uses JDBC, Java’s database access interface, to disable autocommit, write resources and changes, and call db.commit(). It runs rollback() on database errors. HAPI converts the returned MethodOutcome into a create response. The client requests the created representation with Prefer: return=representation. Both sides of the experiment actually passed through HTTP routing, transactions, and the analytics task.
| Name you may encounter | Which work does it take on? |
|---|---|
| HAPI Plain Server | Receives standard requests, parses resources, and calls your methods. Your handler decides how fields map to hospital business tables. |
| HAPI JPA Server | Also supplies existing data access, resource storage, and search implementations. JPA is Java’s interface for relational persistence. For a general service supporting many resources, evaluate the existing implementation first. |
| Spring Boot | Helps configure, wire, and start Java applications. HAPI can run within one. This example starts Jetty directly to make the server-to-handler connection visible. |
JPA Server has its own indexing and query costs. This experiment measured the Plain Server path and does not generalize the numbers to a full service with search, terminology validation, and history retention enabled.5
After the client receives the response, both services share the following processing logic. source reads the corresponding SQLite database and lake points to this test’s Delta directory. write_event transforms the source record into a row and merges it by ID. Readability is recorded only after reopening the table and confirming the same patient ID and family name. Here are the checks from the response to readback of one request.
seq = int(response.headers["X-Change"])
event = dict(source.execute("SELECT * FROM changes WHERE seq=?", (seq,)).fetchone())
assert event["id"] == response.json()["id"]
write_event(event, lake)
assert any(row["id"] == event["id"] and row["family"] == "Lin" for row in read_table(lake))
Where do the milliseconds in the table start?
The local experiment used Python 3.12, JDK 21, and Maven 3.9. Each round started fresh Java and Python services. Each implementation created 25 distinct patients in succession. The first five warmed up parsers, runtimes, and the lake table. The last 20 counted toward the statistics. One request ran at a time, with one lake commit and readback per patient. Replaying a processed event at the end left 25 rows in each table.
All requests start with the local clock when the client is ready to send. Commit is measured immediately after the server commits the transaction. Response received is when the client finishes reading the HTTP response. Readable is when the worker has written, reopened, and verified that row in the lake table. The following milliseconds were recorded while writing this article on one Linux x86-64 machine with an AMD Ryzen 7 8845HS. Versions were fixed at HAPI 8.2.0, Jetty 11.0.25, FastAPI 0.115.12, Uvicorn 0.34.2, and delta-rs 0.25.5. Execution order was reversed between rounds.
| Round order | Intake service | Median commit | Median response received | Median readable in lake |
|---|---|---|---|---|
| Java first | HAPI Plain Server | 8.84 | 10.45 | 41.01 |
| Java first | FastAPI | 7.50 | 8.18 | 39.59 |
| Python first | FastAPI | 7.59 | 8.31 | 39.26 |
| Python first | HAPI Plain Server | 8.95 | 10.59 | 40.86 |
In the Java-first round, the first Java request after warm-up took 9.07 ms from send to commit, 10.76 ms to response receipt, and 34.11 ms to verified readback. Subtracting for that same request, the client waited about 23.35 ms after the response before the patient could be read. Each table column sorts its own 20 measurements and averages the middle two. Those middle positions can belong to different requests in different columns. To measure post-response waits, subtract within each request before aggregating.
In this small serial sample, changing intake service shifted the median time to readability by around 1–2 ms in each round. For both services, committing one lake row and reading it back after the response took longer. Observed differences include framework, driver, and serialization behavior. To choose for peak hospital traffic, repeat with matching concurrency, commit batch sizes, data volumes, and recovery requirements.
Which stage falls behind with four simultaneous requests?
An outpatient system may send several records together. In the second experiment, either one or four client threads continuously sent requests. One background worker wrote events to the lake individually and verified each by readback. Even with one sender, the next request could overlap with ingestion of the previous one. This compares the two actual services at the same concurrency. Python used a synchronous SQLite driver and a synchronous FastAPI route. Switching to an async database driver would be a separate experiment.
Each condition started with a new operational database and lake table, five warm-ups, then 32 requests. Starting when each request was actually sent, I recorded time to HTTP response and time to verified lake readback. P95 is the 31st of the 32 sorted observations. Successful creates per second uses the interval from first send to final response. The two numbers per cell correspond to the Python-first and Java-first rounds, on the same machine with the same one-row commits.
| Intake | Max in flight | Successful creates/s | Response P95 (ms) | Lake readable P95 (ms) |
|---|---|---|---|---|
| FastAPI | 1 | 98.1 / 100.5 | 13.3 / 13.3 | 1747.9 / 1564.8 |
| HAPI | 1 | 69.0 / 66.9 | 18.6 / 19.1 | 1732.2 / 1622.5 |
| FastAPI | 4 | 88.5 / 105.6 | 138.8 / 137.2 | 1933.8 / 1739.3 |
| HAPI | 4 | 82.8 / 97.4 | 133.7 / 100.8 | 1796.0 / 1583.6 |
All eight runs returned 32 successful responses and verified all 32 readbacks. With four threads, both services had tail response latencies over 100 ms, while the last few readbacks in this dataset took seconds. “Readable” includes waiting for the single worker, committing, and verification. To reduce reporting delays, test batch writes separately next. This table cannot predict hospital peak throughput or isolate gains from async syntax itself.
How much does PySpark’s popularity help decide?
Receiving patients in Java does not prevent another program from processing lake data with PySpark, Spark’s Python API. The local experiment used a Python library to write Delta directly, avoiding a Spark cluster startup. For the question “Is PySpark more popular?”, there is dated evidence: Spark author Matei Zaharia’s 2016 talk showed a survey in which 58% of the 2015 sample used Python and 31% Java, compared with 38% for each in 2014. Respondents could use multiple languages. These historical usage figures are not 2025 market shares of all Spark jobs. The 2025 Stack Overflow survey measures language use among developers overall and lacks the Python and Java proportions within the same Spark-user population. That denominator cannot establish a Spark ranking for the year of the question.67
In practice, if the hospital already has a usable HAPI service, checking which resources and history endpoints it exposes may save building an intake service. If the team only needs to map one laboratory message type to an existing hospital API, a Python adapter could deliver the feature. The decision depends on which layers you have to provide. Keep the three milestones above for the day you need to compare performance.
Footnotes
-
Health Level Seven International. (2019). RESTful API. FHIR R4 v4.0.1. Create and success response. ↩
-
Delta Lake contributors. (2025). delta-rs, Python v0.25.5. GitHub. Python table and merge operations. ↩
-
Islam, N., & contributors. (2021). fhir.resources 6.1.0. PyPI. FHIR Version Info and model examples. ↩
-
HAPI FHIR contributors. (2025). HAPI FHIR, v8.2.0. GitHub. Server module. See also HAPI FHIR Documentation, Handling Create and ResourceParam. ↩
-
HAPI FHIR contributors. (2025). JPA server base, v8.2.0. GitHub. JPA implementation · HAPI documentation on resource providers and the data access layer. ↩
-
Zaharia, M. (2016, June 21). What’s changing in big data? USENIX HotCloud. Page 10, Languages Used for Spark in 2014 and 2015. ↩
-
Stack Overflow. (2025). 2025 Developer Survey: Technology. Stack Overflow. Programming, scripting, and markup languages. ↩