What HAPI FHIR referential integrity and cascading deletes change for your data
A team running a HAPI FHIR JPA server often needs to remove data for cleanup or to honor an erasure request without leaving broken references behind. Referential integrity enforcement is the control that decides whether a resource can be written with references that point to nothing, and whether a resource can be deleted while other resources still point to it. HAPI FHIR can enforce this on write and on delete, so the decision is made when data arrives and when it leaves, not after the fact. Without these controls, a deleted Patient can leave Observations, Encounters and other resources that refer to a record which no longer exists, and downstream systems may fail or show misleading results.
The enforcement runs in the application, not in the database, and it only covers references that are indexed by a SearchParameter. That scope matters. A reference field with no indexed SearchParameter is not checked, so a team must confirm which reference paths are indexed in its own server configuration and custom search parameters before relying on the control. Reference checks also add work to every write and delete, so teams should test the effect on bulk loads and batch jobs. Confirm the exact settings for write and delete enforcement in the JPA configuration documentation for the version you run.
Cascading deletes are the opposite choice: instead of blocking a delete, the server removes the resources that refer to the target. With the CascadingDeleteInterceptor registered, a request using _cascade=delete or the X-Cascade: delete header also deletes the referencing resources. Adding _expunge=true runs an asynchronous batch job that expunges the target and the resources that reference it, which is what removes stored history and makes the data unrecoverable from the server. Teams need these controls when they clean up test or retired data, when they handle an erasure request covering a whole patient record, or when they must remove linked data that a clinical system has no business keeping. Each of these uses should be tied to a written rule, and the team should decide in advance which resource types are allowed to cascade.
Which reference and delete options fit which data-cleanup goal
This table compares the reference and delete options available on a HAPI FHIR JPA server, showing what each removes, what it leaves behind and why a team would choose it. Read each row against your cleanup goal, and note that cascading deletes need the CascadingDeleteInterceptor registered on the server.
| Option | What is removed | What is left behind | Typical reason to choose it |
|---|---|---|---|
| Reference enforced on write | Nothing; the write is rejected if the referenced resource does not exist | Existing resources are unchanged | Stops new dangling references at the point data enters the server |
| Reference enforced on delete | Nothing; the delete is rejected while other resources still reference the target | The target and its referencing resources stay in place | Prevents accidental deletion of resources other records depend on |
| Plain delete, no cascade | Only the targeted resource (soft-deleted, so its history remains) | Referencing resources that now point at a deleted resource | Removes one record when its dependents are handled separately |
| Cascading delete with _cascade=delete or X-Cascade: delete | The target plus the resources that reference it, requires CascadingDeleteInterceptor | Stored history and expunged data are not removed by the delete alone | Removes a related set of records in one request while keeping the history |
| Cascading delete with _expunge=true | The target and referencing resources, expunged from the database by an asynchronous batch job | Little beyond the job's own record, so confirm completion and any remaining history | Erasing data for cleanup or erasure requests where stored versions must also go |
How the application checks references on write and delete
HAPI FHIR enforces referential integrity in the application layer, not in the database. The relational schema behind the JPA server does not carry foreign key constraints between resource tables, so a reference is validated by HAPI FHIR when a resource is written or deleted. That distinction matters for operators: anything that writes to the database directly, bypasses the server, or runs a bulk load outside the normal request path will not be checked by the database. Plan your data loading and any maintenance scripts with that in mind, and treat the server as the only enforcement point.
The check only covers references indexed by a SearchParameter. If a reference element has no SearchParameter that indexes it, HAPI FHIR cannot see it during the check, so a dangling reference can be stored without error. Before you rely on the check, list every reference element your profiles and implementation guides use, then confirm with the server's CapabilityStatement and your SearchParameter resources that each one is indexed. Custom profiles and extensions are the usual gap, so review them first. Do not assume that a reference element is covered because the base specification defines a search parameter for it.
Confirm the enforcement settings in the HAPI FHIR JPA configuration documentation for your exact release rather than relying on defaults or on examples from older blog posts. The relevant options control whether references must resolve on write and on delete, and the names and defaults have changed across versions, so record the key names, values and the version they apply to in your deployment standards. Then test both paths in a non-production environment: create a resource with an unresolved reference, and attempt to delete a resource that other resources still point to. The results of those two tests define the baseline that your cascade and cleanup design builds on.
How a delete request moves through referential checks, cascade and expunge
The request starts at the client, which sends a DELETE with or without _cascade=delete, the X-Cascade: delete header, or _expunge=true. The server first checks whether the target is referenced by another resource. If it is and cascade is not set, the plain delete is blocked. If cascade is set, the CascadingDeleteInterceptor removes the referencing resources, and _expunge=true hands the target and its referrers to an asynchronous batch job. Check that the referencing elements are covered by an indexed SearchParameter, because referential checks only see indexed references.
Branches a DELETE takes through reference checks, cascade and expunge on a HAPI FHIR JPA server.
What cascade deletes and expunge each remove from the server
HAPI FHIR separates a logical delete from the physical removal that expunge performs, and cascading adds reach to referencing resources. Each card below covers one of these behaviors, so you can see what each request removes, what it leaves behind, and what your team must confirm before using it for cleanup or erasure.
Standard delete is logical
A plain DELETE marks the target resource as deleted on the server. That step is a logical operation, so the stored data is not physically removed by the delete alone. When referential integrity is enforced on delete, the server can refuse the request while other resources still point at the target. Check this behavior in your version before relying on plain deletes for data cleanup.
Cascade delete removes referrers
With the CascadingDeleteInterceptor registered, a delete request carrying _cascade=delete or the X-Cascade: delete header also deletes the resources that reference the target. The effect reaches beyond the resource named in the URL, so one request can remove records that no one selected individually. Map the reference paths for each resource type before enabling it, and restrict which clients can send these requests.
Cascade with expunge runs a batch
Adding _expunge=true to a cascading delete starts an asynchronous batch job that expunges the target and the resources referencing it. Removal is therefore not complete when the HTTP response returns. Plan to monitor the job until it finishes and to log its outcome, since a failed or partial run needs follow-up. Confirm how your version reports job status in the JPA configuration docs.
History and version effects
The logical delete and the physical expunge have different effects on what remains on the server. Confirm how deleted versions appear in history in your release, because that determines what a reader of the history can still see after a delete. Test this on a copy of your data before an erasure process depends on it. Backups and replicas may also hold earlier copies, so record that scope in your data handling notes.
Setting up referential integrity and cascade deletes in HAPI FHIR
This sequence turns on reference checks for the elements your data model depends on, adds cascading delete behavior, and records how plain deletes, cascade deletes and expunge behave in a non-production server before any of it reaches production.
Inventory the reference elements to enforce
The data governance or integration lead and a FHIR developer list every reference element that must resolve on write and delete, such as Observation.subject or Encounter.subject. For each element, confirm that the server has a SearchParameter indexing it, because HAPI FHIR only checks references that a SearchParameter indexes. Record any reference without an index as a gap to fix before enabling checks. The list is done when every enforced reference has a named SearchParameter and the gaps are assigned to an owner.
Confirm the server version and Java runtime
The platform engineer checks the HAPI FHIR version in use against the versions page and confirms the JDK it runs on meets that version's requirement. HAPI FHIR 8.2.0 requires JDK 17, so confirm the runtime for the version you run. Note the version in the test record, because reference handling and interceptor behavior can change between releases. The check is complete when the running server reports the expected version and the JDK matches the documented requirement.
Enable write and delete reference checks
The FHIR developer enables reference enforcement in the JPA server configuration for both writes and deletes, using the settings described in the JPA configuration documentation. Apply the change to a non-production environment only and restart the server. Confirm the setting is active by sending a create request for an Observation that points to a Patient ID that does not exist. The server must reject the request with a reference error, which is the verification check for write enforcement.
Register the cascading delete interceptor
The FHIR developer registers the CascadingDeleteInterceptor with the JPA server so that cascade requests are honored. Keep the registration limited to the environments where cascade has been approved, and record the change in the configuration repository. Verify registration by reviewing server startup logs and by sending a test delete with the cascade parameter. The step is complete when the interceptor is confirmed active and the test delete returns a response rather than an unhandled error.
Test a plain delete against a referenced resource
With a Patient that has at least one referencing Observation loaded in the test environment, the tester sends a plain DELETE for the Patient without any cascade parameter or header. The server must return a conflict response and must leave both resources in place. Then confirm the Observation still exists with its reference intact. This is the key negative test: if the Patient is deleted or the Observation loses its reference, stop and review the delete reference check before going further.
Test cascade delete with and without expunge
The tester runs two cascade deletes on separate copies of the test data. The first uses _cascade=delete or the X-Cascade: delete header without _expunge, then confirms the Patient and referencing Observations are marked deleted. The second adds _expunge=true, which starts an asynchronous batch job, so the tester polls for completion and then searches for the resources and their history to confirm they are gone. Compare the two outcomes and record any resources that remain unexpectedly.
Record results and approve the configuration
The tester writes a short test record listing the server version, configuration values, interceptor registration, each test case, the expected result and the observed result. The data owner and security lead review the record and decide whether cascade and expunge may be used in production, and under which roles. The step is done when the signed record exists and any failed test has a fix and a retest scheduled.
How cascading deletes fit GDPR erasure requests
A cascading delete is one step in an erasure workflow, not the whole workflow. Removing a Patient or other resource through HAPI FHIR determines only what the server removes from its own resource tables. Personal data can still sit in resources that reference the deleted record if they were not cascaded, in version history, in database and filesystem backups, in audit logs written by your audit tooling, and in files already produced by exports or shared with other systems. Before running a delete, map where the subject's data lives across these locations and decide which ones your erasure procedure must reach.
The controller, not the server, decides the legal basis for erasure, any exemptions that apply, and how long records must be kept for clinical, legal or financial reasons. Those decisions belong with counsel and your data protection officer, and they may differ by jurisdiction and by record type. HAPI FHIR behavior then determines what the server actually removes: confirm in a test environment whether your configured interceptors cascade the deletes you expect, whether _expunge=true is used, and how the server treats history for the resources involved. Do not assume that a successful response means every copy of the data is gone.
Document each erasure step your team runs, including the request and cascade parameters, the expunge job identifier, the backup retention period and the systems you checked, and keep that record with the request. Ask your compliance function to review the procedure and sign off on the evidence it produces, and agree in advance how exceptions such as retained clinical records will be handled and recorded. An independent auditor or regulator will judge the outcome, so the documentation should show what was done and why, not only that a delete call returned success.
Security and audit risks of cascading deletes
Cascading deletes and expunge remove data in bulk, which makes them among the most sensitive operations on a HAPI FHIR JPA server. The four risks below cover who can trigger them, what evidence survives, how far a single request can reach, and where deleted data still sits after the server has forgotten it.
Who can send cascade and expunge
Both _cascade=delete and the X-Cascade: delete header are ordinary request parameters, so any client that can call DELETE can ask for a cascade. Restrict delete and expunge operations to a small set of administrative roles using the AuthorizationInterceptor, and test that a standard clinical or application role receives a denial on a cascading delete and on _expunge=true. Confirm that your identity provider cannot pass these roles through a broad default group.
Proving what was removed
A cascade can remove many resources, and the request that triggered it may not show their identifiers. Confirm that BALP audit logging captures each delete and the caller identity, and that server logs record the cascade parameter and the expunge job that followed. Decide in advance how you will reconstruct a deleted set of resources for an investigation, because an expunged resource is not recoverable from the live database.
Mass deletion from one request
A single delete on a widely referenced resource, such as an Organization or a Patient, can reach every resource that points to it. Illustratively, a mistaken delete of a shared parent could remove thousands of dependent records in one call. Ask whether your change process requires a second approver for cascading deletes, whether a staging environment mirrors production volumes for rehearsal, and whether alerts fire when cascade counts exceed an agreed threshold.
Backups and replicas keep deleted data
Expunge removes rows from the running server, but database backups, point-in-time recovery archives, read replicas and reporting copies still contain the data until they age out. Document each copy, its retention period and who can restore it, and plan how a restore will re-apply deletions so erased records do not return. Check this against the erasure procedure in your privacy program before you rely on cascade and expunge for data removal.
Cost, effort and what cascade delete work needs from your team
What drives the effort of enabling referential integrity checks in HAPI FHIR?
The effort depends mostly on how many resource types reference each other and how many of those references already contain dangling data. Enforcing referential integrity on write and delete is a configuration decision, but it only protects references that are indexed by a SearchParameter, so the first task is mapping which references matter and confirming each one is indexed. Teams with a small, well-documented resource model usually finish this faster than teams that inherited years of loosely linked data. Ask any partner to list the resource types, reference paths and SearchParameters they will check, and to state how existing bad references will be found and reported before enforcement is switched on. A write-side rule that rejects new writes can break integrations that currently succeed, so the scope should name the upstream systems that must be tested with it. Costs rise with the number of integrating systems, the number of reference paths, and the amount of remediation of historical data.
Can cascade deletes be tested safely in a staging environment first?
Yes, and you should test them there before any production change, because a cascading delete removes referencing resources as well as the target. Build staging from a recent, de-identified copy of production data so that the reference graph has the same shape as the real one. Then run deletes against known test patients or encounters, confirm which resources are removed, and compare counts before and after. Test both the _cascade=delete query parameter and the X-Cascade: delete header, because the scope of what each removes should match your intent. Record the results as evidence, including what happened to resources in other partitions or with references from systems outside the server. Staging tests should also cover the _expunge=true path, which runs as an asynchronous batch job, so the team can observe how long it runs and how it reports completion. Ask the partner to deliver the test plan, the test data set and the recorded outcomes as part of the scope.
How long does this work take, and why does the duration vary so much?
Duration depends on the state of your data and your approval process, and no fixed figure applies across deployments. The largest variables are the number of reference paths to check, the volume of existing records that must be scanned for broken references, the number of integrations that need regression testing, and how many environments must be prepared. Work that includes the cleanup of historical references usually takes longer than work that only turns on checks for new writes. Compliance review cycles, change windows and the availability of the people who own each upstream system can also set the pace more than the technical work does. Ask for a written schedule with milestones for discovery, staging validation, production rollout and handover, and ask which items depend on your teams. Any timeline that is not tied to a written scope with named deliverables should be treated as an estimate rather than a commitment.
What must our team provide before a partner can start?
Three inputs make the largest difference: a data inventory, a reference map and a compliance sign-off. The data inventory lists which resource types hold personal data, where they are stored, and which systems write to them. The reference map lists each reference path, the SearchParameter that indexes it, and the business meaning of the relationship, such as whether a deleted patient should remove its observations. The compliance sign-off records who approves deletion rules, including how cascading deletes map to retention schedules and erasure requests under your own policies. Without these inputs, a partner can only guess which deletes are intended, which creates risk. Also provide access to a staging server, a recent test data copy, the list of integrating systems and their owners, and a named decision maker for rollback. Ask the partner to confirm in writing which of these inputs are required before work begins and which are produced during the engagement.
Can our internal team implement referential integrity and cascading deletes alone?
An internal team with HAPI FHIR JPA server experience, a working test environment and clear data ownership can usually handle the configuration itself. The harder parts are often the review: deciding which deletes are legally and clinically appropriate, proving that cascades do not remove data that must be retained, and documenting the result for auditors. Consider whether your team has people who understand FHIR reference semantics, the server's interceptor configuration, and the regulatory rules for erasure. If one of those is missing, an outside partner can supply that skill for a defined scope. DeployOpen implements and hardens self-hosted open-source platforms in infrastructure you control and prepares evidence for compliance assessments, but it does not issue audit reports or certifications, so independent auditors still judge the result. Decide early which parts you will own so that handover is planned, not improvised.
What recurring work follows after cascade delete rules go live?
Recurring work includes reviewing new reference paths whenever the data model changes, updating tests when integrations change, and running the delete procedures under change control. Each HAPI FHIR upgrade can change how interceptors and configuration behave, so the team should retest cascade and referential rules before adopting a new version. Operations staff also need a routine for monitoring expunge batch jobs, investigating failed deletes, and confirming that erasure requests are handled according to policy. These are ongoing costs, and they are usually staffed internally or covered by a support retainer. DeployOpen offers ongoing support, upgrades and continuous testing as retainers. Ask any partner to separate one-time implementation costs from recurring operational costs in the quote, and to state how upgrades, retests and incident response are priced and scheduled.
What should a written scope for this work include?
A written scope should name the server version, the resource types and reference paths in scope, the SearchParameters that index them, and the interceptors to be enabled. It should list the deliverables, such as a configuration record, a test plan with recorded results, a runbook for cascading deletes and expunge jobs, and a handover session. It should state which environments are covered, which integrations will be regression tested, and how historical broken references will be reported. Include the compliance inputs you are responsible for, the approvals required before production, and the rollback procedure. Finally, ask for exclusions in plain language, such as data cleanup outside the server or changes to upstream systems. A quote that follows from this scope is easier to compare across vendors than a quote based on a general description of the work. DeployOpen does not publish a price list, and a quote follows from the written scope.
Limits to confirm in your environment before enabling cascade deletes
Cascading deletes and referential checks in HAPI FHIR depend on how the server is configured, which references it indexes, and which version you run. The cards below list the documented limits to confirm with the HAPI FHIR documentation and with your own tests before any delete path reaches production data.
Integrity covers only indexed references
Referential integrity is enforced only for references that a SearchParameter indexes. A reference path with no indexed SearchParameter is not checked on write or delete, so a dangling reference can persist silently. Before enabling enforcement, list every reference element your profiles use and confirm each one has an indexed SearchParameter. Test a write with an unresolvable reference on each path to confirm the server rejects it as expected.
JPA configuration docsChecks run in the application
Referential checks run in the HAPI FHIR application layer, not as foreign key constraints in the database. Writes that bypass the server, such as direct SQL, bulk loads through other tools, or manual database repairs, are not checked. Confirm which ingestion paths reach the server and which write directly to the database. Document that database-level changes need their own integrity review.
Expunge runs as an asynchronous job
With _expunge=true, the expunge work runs as an asynchronous batch job rather than inside the delete request. The client receives a response before the data is gone, so a successful response does not confirm erasure. Monitor job status, confirm completion, and check that the expunged resources no longer return from search, history and direct reads. Plan this monitoring before you rely on the job for erasure requests.
Interceptor must be registered
Cascading deletes work only when the CascadingDeleteInterceptor is registered with the server. Without it, _cascade=delete and the X-Cascade header have no effect, and a delete can fail on referenced resources instead. Verify registration in each deployed instance, including any instance added by scaling or by a configuration change. Test cascade behavior on every environment, because a missing registration on one instance can produce different results.
Confirm the JPA version and runtime
Cascade and expunge behavior can change between HAPI FHIR releases, so confirm it against the version you run, not against older examples. HAPI FHIR 8.2.0 requires JDK 17. Check the version requirements for your target release on the versions page, and rerun your delete and expunge tests after every upgrade before the change reaches production.
Versions pageHow DeployOpen scopes and delivers HAPI FHIR referential integrity work
DeployOpen approaches referential integrity and cascading deletes in HAPI FHIR as a scoped change to a self-hosted server in your own infrastructure. We map which references must resolve, which delete paths are allowed, and how erasure and cleanup requests will be handled before any interceptor is registered. Engagements are fixed-scope, with the scope agreed in writing before work starts.
How we scope
- Inventory which references are indexed by a SearchParameter, since only those are checked by HAPI FHIR referential integrity.
- Agree in writing which resource types may be deleted with cascade, and which must block deletes while referenced.
- Document the erasure request path, including whether _expunge is permitted and who approves it.
How we build
- Configure referential integrity on write and delete in the JPA server settings for your environment and test each setting.
- Register the CascadingDeleteInterceptor only on endpoints and roles approved in the scope, and restrict clients that send the cascade header.
- Test cascade with and without _expunge on copied data, including the asynchronous batch job, before any production run.
How we hand over
- Deliver written runbooks for cascade deletes, expunge jobs, and the checks to run afterward against your database.
- Provide test evidence showing blocked deletes, cascaded deletes and expunged resources, mapped to your erasure procedure.
- Walk your platform, security and compliance teams through the configuration so they can review it independently.
How we support
- Offer ongoing support, upgrades and continuous testing as a retainer after handover, if your team wants it.
- Retest referential integrity and delete controls after HAPI FHIR version upgrades or interceptor configuration changes.
- Confirm with your legal and privacy advisers how erasure obligations map to your retention and backup settings.

