Offline Sync Design
SPICE's mobile app is offline-first. Health workers register households, screen members and record assessments with no connectivity, and the data is reconciled with the server when a connection is available. This page describes how the app and the server stay consistent.
Design principles
The device is always usable. Every write goes to the local database first. The network is never on the path of a user action.
Upload is asynchronous. The server accepts a batch quickly, stores it durably, and processes it in the background. The device then asks for the result.
Every record carries a client-generated transaction ID. Retries from the device or the server are therefore safe, and the server never creates a duplicate.
The device learns the outcome per record. Status is reported back individually, so one failed record does not block the others.
Download is incremental. After the initial load, the device only fetches what changed since its last successful sync.
Components
Mobile app
Local encrypted database, a record of each record's sync state, background workers, upload and download logic.
Offline sync service
Accepts uploads, de-duplicates, queues work, processes queued records, tracks per-record status, serves download slices.
Message queue
Decouples acceptance from processing. RabbitMQ is supported, as are other queues listed in the service configuration.
Platform services and FHIR mapper
Receive the processed records and write them as FHIR resources. See FHIR & Standards.
PostgreSQL, cache, object storage
Sync bookkeeping, short-lived credential caching, and optional pre-built initial-download files.
On the device
Local store. An encrypted relational database on the device holds households, members, assessments, follow-ups, reference data and downloaded history. Each synced entity has a sync state and a transaction ID.
Record states. A record moves through the following states.
Not synced
Created or edited locally, waiting to be uploaded.
In progress
Included in an upload whose outcome is not yet known. It is excluded from further uploads.
Success
The server confirmed the record and returned its server-side ID.
Failed
The server rejected or could not process the record.
Network error
The upload did not reach the server. The record will be retried.
What triggers a sync
Saving a record (registration, assessment, follow-up)
Starts a background sync, which runs when the device has a network connection. Only one such job is queued at a time.
App landing screen
Starts the same background sync.
User taps sync
Runs the upload and then polls for the status, showing progress.
First launch or after reinstall
Initial load of data, described below.
Upload
A sync pass collects every record that is not yet synced (households together with their members, other members, assessments and follow-ups) and sends them to the server in one upload request tagged with a unique request ID. Before sending, the app:
Makes sure every record has a transaction ID, and saves any newly assigned ID so a retry reuses it.
Marks the included records as in progress.
Durably saves the request ID, so the next pass knows an outcome is pending even if the app is killed mid-request.
The server's synchronous reply is not used as the result. The app treats it as "submitted" and finds out the real outcome by polling the status endpoint.
A background pass has this order: resolve the status of any previous request, upload new changes, wait for the status, then download changes. If the status of a request cannot be resolved the pass stops, and it is retried on the next trigger.
On the server
Accepting an upload
The service checks that the request has an ID. If it has already seen that ID, it skips the work and returns success, so a retried upload is harmless.
It splits the upload into units of work: one per household (with its nested members), one per group of members, and one per member's assessments and follow-ups.
It checks every record's transaction ID against what it has already stored. Records already seen are dropped. If the same ID appears twice in a single upload, the repeats are recorded as failed rather than processed.
It saves each unit as a row marked in progress, then publishes one queue message per row. Messages are published in groups of ten when an upload is large.
The call returns once this is done. Nothing is written to FHIR on the request thread.
Asynchronous processing
A queue consumer picks up each message, loads the stored row and processes it by type:
Household (with members): create or update the household through the platform services, then process the members nested in it and link them.
Member: create or update each member.
Assessments and follow-ups for a member: process follow-ups first, then assessments.
Follow-up (call-based workflows): record the follow-up and the call register details.
Each of these calls the platform services, which use the FHIR mapper to write the resources (see FHIR & Standards). The processor acts as a dedicated service user and passes the original author's identity on, so provenance reflects the health worker who recorded the data, not the service.
The consumers run with a configurable level of concurrency.
Ordering, idempotency and retry
Idempotency
Request ID de-duplication at the upload, and transaction ID de-duplication per record, backed by a uniqueness constraint. Concurrent duplicates that slip past the check are caught by the constraint and skipped.
Ordering
Dependencies are handled inside a unit of work: a household is written before its members, and follow-ups are written before assessments. Across units there is no ordering guarantee, so a member's data is designed to reference parents already known to the device or included in the same upload.
Transient failures
Dependency timeouts, connection resets and gateway errors are retried by re-queuing the message, up to three times.
Permanent failures
Validation errors, and failures that keep recurring after the retries, mark the record failed with the error recorded.
Safe-to-repeat only
Automatic HTTP-level retries only apply to read calls. Writes are never repeated blindly. They are retried through the queue, where the transaction ID makes a repeat safe.
Manual recovery
Support staff can list failed records and re-queue them, filtered by a classification of the error (transient, deterministic, unknown), without database or queue access.
Conflict behaviour
There is no field-level merge. Each upload carries the record as the device last saw it, and the server applies it as a create or an update of the whole record. Updates create a new version of the FHIR resource, so earlier versions are kept in the resource history. The last upload to be processed is the current one.
Reporting status back
The device polls with its request ID. The service replies with one entry per record: its type, the device's reference ID, its status and, once successful, the server-side ID. The app:
stores the server ID on success,
marks the record failed on failure,
keeps waiting while anything is still in progress.
If the server has no record of the request ID (for example, the upload never arrived), the app moves every in progress record back to network error so that the next pass resends it. Because the server de-duplicates by transaction ID, resending a record that had in fact arrived is harmless.
Download and initial load
Initial load. On first launch (and after reinstall, device replacement or a cleared local database) the app clears local clinical data and downloads everything in scope for the user, based on the user's assigned villages or areas.
Incremental sync. Each later download sends the last sync time the server returned and gets only changes since then. The app keeps one cursor per data slice (households, members, follow-ups) and uses the oldest as the combined cursor. It always uses the server-supplied time, never the device clock.
Slices. Households, members and follow-ups are requested in parallel. Assessment history, including pregnancy episodes, is fetched afterwards. For some roles the history is selected by the members the user has served rather than by area.
Server fan-out. For each slice the service calls the platform services in parallel on a bounded thread pool, within a time limit. If a dependency is slow or fails, the request fails fast instead of holding a connection open.
Local persist. The device saves each download in bulk, and only updates its cursors after the data is stored.
Pre-built initial downloads (optional). An opt-in nightly job can build each user's first-sync data into stored files in object storage, and serve them on first sync instead of assembling the data per request. It falls back to live assembly if a file is missing or the user's scope has changed. It is off by default.
Deletions. A delta cannot express removal, so records that leave a user's scope are corrected at the next full download.
Failure modes and how users see them
No connectivity during upload
Records stay not synced or return to network error.
Nothing blocks the work. Records sync on the next trigger. A manual sync reports "no network".
App killed or low memory mid-upload
The pending request ID survives. The next pass resolves it and reverts records if needed.
Records appear again as pending and are re-sent.
Upload accepted, processing fails transiently
Re-queued up to three times.
Status stays in progress, then resolves.
Upload accepted, record is invalid
Record marked failed with a reason.
Failed status for that record. Others are unaffected.
Processing service credentials invalid or dependency down
Rows fail with a classification that allows bulk re-queue once fixed.
Delayed sync, with no data loss. Support can re-queue.
Status polling gives up
The background job ends and retries on the next trigger.
Sync completion shown as failed, with a retry option in manual sync.
Download fails or times out
Cursors are not advanced.
Sync reported as failed. The next attempt starts from the same cursor.
Scaling considerations
Accepting an upload is cheap and independent of processing speed, so bursts (for example many workers syncing at day's end) are absorbed by the queue.
The processing rate is limited by the downstream services and the FHIR server, not by the queue. Scale consumer concurrency together with the mapper and the database, and watch downstream latency.
A first-time download is the heaviest operation, because it assembles a user's whole scope across several services. Fan-out is bounded, and optional pre-built files remove that load from peak hours.
Keep upload batches reasonably small, and keep the device's request timeout generous for large initial downloads on poor networks.
Several service replicas can consume the same queue. Duplicate-safety rests on the transaction ID constraint and not on a single consumer.
Last updated