How do you implement FHIR R4 POST /Subscription so an updated lab result actually reaches a lake table?

August 13, 2025

At 10:30 in the morning, the lab releases a platelet result of 220 for order 17. The doctor can already see it in the EHR, but the analyst opens a report and it isn't there. These are two copies of the data: the EHR holds clinical records, while the analytics program organizes records from many people into tables that can be queried together. This example writes such a table to a local directory and uses Delta Lake to manage its files and versions. At the end you can read the row back yourself.

I once asked if we could add a hook that sent newly created or updated resources to a data lake. A callback means I supply an address in advance so the other party can notify me when something happens. After seeing POST /Subscription, I followed up: “这个FHIR服务注册服务器是怎么实现的” (“How is this FHIR registration server implemented?”). To answer, we need to see when each of the following three pieces of code runs.

sequenceDiagram
    participant A as 分析程序
    participant F as 病历服务
    participant L as 湖表
    A->>F: 在 /Subscription 留下条件和接收地址
    F-->>A: 已登记并激活
    Note over F: 新结果符合条件,保存结果和待发通知
    F->>A: 向 /notify 发送通知
    A-->>F: 已记下待办
    A->>F: 从上次位置补读变更
    A->>L: 按结果 ID 写入较新的版本

The analytics program leaves its criteria and receiver address at the EHR's /Subscription endpoint. The EHR confirms registration and activation. When a new result matches, it stores both the result and a pending notification, then notifies /notify. The receiver records the work before acknowledging. The analytics program reads changes since its last position and writes the newer version to the lake table by result ID.

Follow a disconnection through the diagram. When the EHR saves 220, analytics happens to be offline. After it comes back, it receives the retried notification, then reads the actual value from the EHR. First we'll see how notifications are registered and retried. Finally a one-row lake table will show which value survives a replay of an old result.

Who implements the registration endpoint, and who implements the receiver?

The EHR service implements POST /Subscription. The requester submits a FHIR resource, a record organized according to the health data exchange standard, meaning “please notify me of changes like these.” Here's the request body in this example. The experiment dynamically allocates local ports on each run, replacing PORT with the actual number.

{
  "resourceType": "Subscription",
  "status": "requested",
  "reason": "Follow verified lab results",
  "criteria": "Observation?status=final,corrected",
  "channel": {"type": "rest-hook", "endpoint": "http://127.0.0.1:PORT/notify"}
}

An Observation is a measurement. The criteria select finalized or corrected results. A status of requested asks to establish the subscription. Once the EHR service confirms it can fulfill it, the service sets the status to active and saves it. This teaching service implements only the filter shown and one preconfigured callback address. It explicitly rejects other conditions so they can't appear to register successfully but never match. After restart, it can still read the subscription from disk.1

Registration is also a database write. The following excerpts show two parts of the registration function: the first accepts the request and checks its criteria; the second saves the destination address and criteria in the same subscription record. The actual service also checks status, notification type, and duplicate registrations. A retry with the same configuration returns the existing record; the same ID with different settings returns a conflict.

@app.post("/Subscription")
def register(sub: Subscription):
    endpoint = os.environ["CALLBACK_URL"]  # 分析端预先约好的本机收件地址
    if sub.criteria != "Observation?status=final,corrected" or sub.channel.endpoint != endpoint:
        raise HTTPException(400, "Unsupported subscription")
    sub.id, sub.status = "lab", "active"
    with database() as db:
        # 节选首次登记的路径;订阅正文也保存了 channel.endpoint。
        db.execute("INSERT INTO subscriptions VALUES ('lab',?)", (sub.json(),))
    return response(json.loads(sub.json()), 201, {"Location": "/Subscription/lab"})

The analytics program implements a different endpoint, POST /notify. This example uses an R4 notification with an empty body. Receiving it tells you only that it's time to check. The notification contains neither a patient ID nor the platelet value. The receiver first writes a work item in its own SQLite database, then returns 204 to acknowledge receipt. If ten notifications arrive close together, one “needs fetching” marker is enough. The ingestion job reads the actual resources, prepares the fields, and commits the lake table. To make ordering visible in the terminal, the experiment invokes delivery and ingestion in steps. Normally a long-running process or scheduler can run them.1

The receiver is short. The pending table keeps one row for this subscription. Each wake-up increments a counter. The handler clears the row only if there hasn't been a newer wake-up. Even if a new notification arrives just as a read finishes, there's still a way to see the pending work. When the ingestion job finds this item, it resumes fetching changes from its last recorded position.

@receiver.post("/notify")
def notify():
    with closing(analytics()) as db, db:
        db.execute("""INSERT INTO pending VALUES (1, 1)
                      ON CONFLICT(id) DO UPDATE SET generation = generation + 1""")
    return Response(status_code=204)

When saving 220, how do we ensure that a notification is still due after a restart?

Suppose the EHR first saves 220 and then contacts analytics over the network. If power fails between those steps, the clinical record survives, but nothing remembers the notification. The example puts three rows in the same database transaction, committing the changes as one unit: the resource's current value, an ordered change record, and a pending delivery job for a matching subscription. Here is the core of store_result, omitting duplicate-version checks. The sender contacts the receiver only after commit.

# db 是病历端同一个 SQLite 连接,以下写入一起提交。
db.execute("INSERT OR REPLACE INTO resources VALUES ('Observation',?,?,?)",
           (rid, revision, body))
seq = append_change(db, "Observation", rid, body)
if resource.status in {"final", "corrected"} and subscription_exists:
    db.execute("INSERT INTO delivery VALUES (?,?)", (seq, endpoint))

The sender takes a job from delivery and deletes it only after a successful POST. If the receiver is offline, the job remains for retry. If the receiver has accepted it but the sender crashes before deletion, the next attempt may send it again. An empty notification therefore serves only to wake the consumer. Downstream processing still needs to tolerate rereading the same version.

The experimental EHR also exposes a teaching endpoint, GET /demo/changes?after=1. It returns changes after event 1 in commit order, including deletions. Creating Lin is event 1 and the value 220 for order 17 is event 2. The ingestion job remembers the last processed sequence number and can resume after restart. This ordered endpoint is an extra facility supplied by the experiment. When integrating with someone else's FHIR service, check what it provides for resource history, pagination, deletions, and retention. A subscription endpoint alone doesn't promise indefinite replay.2

How can we tell that 218 has reached the analytics table?

The original 220 and its correction to 218 share one result ID. The analytics table recognizes a row by resource type plus resource ID, then uses the source commit sequence number to decide whether to overwrite it. The statement below expresses what the example does with Delta Lake's merge. Here s is the incoming row and t the existing lake row. This example has one ingestion process handling one source event at a time.3

MERGE INTO lab AS t USING incoming AS s
ON s.kind = t.kind AND s.id = t.id
WHEN MATCHED AND s.seq > t.seq THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *

The processing checkpoint advances only after the lake table commit. If the job exits after the commit succeeds but before saving progress, the same event replays, but its old sequence number can't overwrite a newer value. The example also keeps a visible field so report queries display only current valid rows. A deletion leaves a versioned marker too; otherwise a late old message could insert a deleted record again.

📓 Note: A delivery job's sequence number, the source sequence in a lake row, and Delta's table-wide version count different things. To find which source record got in, look at the row's seq. To reread a particular whole-table commit, use the Delta table version.

Take the receiver offline, then make one correction fail

I started the EHR service locally, left the notification receiver offline, and published a fictional result. Then I brought the receiver back, sent corrections, and replayed an old event. After each step I reopened the lake table and queried the same result ID. Here are the observations from that run.

ExperimentActual observationWhat it shows
Register the subscription, leave the receiver offline, and publish 220The EHR saved the value and the notification stayed in the delivery queueLosing connectivity didn't roll back a result the doctor could already see.
Start the receiver, retry, and send an extra identical notificationThe lake held one row for this result, with value 220The notification count can differ from the result row count.
The lab corrects the value to 218The same row becomes 218Corrections update by result identity.
The next correction is 217 but uses an unmapped unit, LAB9Source event 4 enters the failure table; the lake still shows 218Progress can advance while a gap remains in the report.
A recognizable correction of 216 arrives first; then fix the unit mapping and replay 217The failure table clears and the lake keeps the newer 216Repairing an old event doesn't move current state backward.
Mark the result entered in error; in a later round restore validity and then delete itNeither exit produces a notification; a catch-up read removes the result from the active listReconciliation is needed even when the network is healthy.

The failure table is a simple dead-letter queue retaining the original event, sequence number, and reason. This example allows retry only after the lab confirms that LAB9 is equivalent to the original unit. Other errors may need a source correction. After recovery, check both the failure table and the actual value for order 17.

The last two steps are easy to overlook. FHIR R4 matches subscriptions against the new state. Once the result enters entered-in-error, it no longer matches. Deletion doesn't trigger this notification either. The experiment detects both exits by actively rereading source changes. If the hospital permits only reading the current list, periodically fetch the whole list and reconcile missing IDs. That repairs today's list, but can't reconstruct every withdrawal between two reads.1

To verify just “replaying 217 leaves 216,” create a one-row Delta table. In Python 3.12, run python -m pip install deltalake==0.25.5 pyarrow==19.0.1, save the following as replay.py, and run python replay.py. This fixes the order and result in question. The numbers 5 and 4 are the source event sequence numbers of the two corrections in the table above.

from tempfile import TemporaryDirectory
import pyarrow as pa
from deltalake import DeltaTable, write_deltalake

def result(seq, value):
    return pa.table({"id": ["L91-PLT-1"], "seq": [seq], "value": [value]})

with TemporaryDirectory() as path:
    write_deltalake(path, result(5, 216))
    table = DeltaTable(path)
    merge = table.merge(result(4, 217), "s.id = t.id",
                        source_alias="s", target_alias="t")
    merge.when_matched_update_all(predicate="s.seq > t.seq").execute()
    print(DeltaTable(path).to_pyarrow_table().to_pylist())

Reading back gives one row with seq 5 and value 216. Change the replay sequence to 6 and rerun; the value becomes 217. The temporary directory is recreated each time, so only the version check accounts for the difference.

💡 Tip: When two interfaces are both called hooks, ask “Who's waiting for an answer?” When the doctor signs an order and calls clinical decision support, the doctor needs a suggestion in the UI. Here the analyst wants to know when committed data reaches the lake. The endpoint of that question is reopening the table and actually finding 218, rather than seeing “notification successful” in a log.

For a source business database that keeps changing, see Snapshots, frequent updates, and the recovery boundary. To compare the intake service across languages, see Timing the same create request in Java and Python.

Footnotes

  1. Health Level Seven International. (2019). Subscription. FHIR R4 v4.0.1. §2.46.1, match scope, exits, deletions, and rest-hook notifications. ↩ ↩2 ↩3

  2. Health Level Seven International. (2019). RESTful API. FHIR R4 v4.0.1. History responses, deletion records, and time ranges. ↩

  3. Delta Lake contributors. (2025). delta-rs, Python v0.25.5. GitHub. Python table interface and merge operations. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-08-13). How do you implement FHIR R4 POST /Subscription so an updated lab result actually reaches a lake table?. https://caiborui.com/blog/2025-08-13-zh-fhir-subscription-to-delta-lake-entrans

@misc{borui2025-f33a0b86,
  author = {borui},
  title = {{How do you implement FHIR R4 POST /Subscription so an updated lab result actually reaches a lake table?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-08-13-zh-fhir-subscription-to-delta-lake-entrans}
}