Skip to content

Offline operation and sync

A warehouse, a basement, a road, a farm. A technician opens the Mateu app on the phone and there is no signal. With offline operation the app keeps working: the work orders are on the phone, the technician searches them, opens one they never opened before, changes its status, writes an inspection and takes a photo. When the connection is back, the phone sends the changes and fetches what changed on the server.

To do that, some data has to live on the device. You say which data, and which screens work on it. Nothing goes to a device unless the app declares it.

The same works in the browser with the Vaadin renderer — see Offline operation in the browser for what is different there (where the data lives, encryption, the service worker).

This page is the guide. The wire actions are in the offline sync protocol, and the field service walkthrough runs the demo end to end.

Each set of records — a dataset — travels one way, or both:

DirectionExampleOn the device
Down (server → device)products, price lists, customers, checklistsa read-only copy
Up (device → server)inspections, meter readings, delivery notes, photoscreated here, sent, then forgotten (unless keepAfterPush)
Boththe work orders assigned to a technician, a van’s stockread and changed here and on the server, so conflicts can happen

What an app takes offline is written in one place, so a reviewer reads it at a glance: specs/ui/offline.yaml. It lists the datasets and the screens that keep working without connection. This is the manifest of the field service demo:

type: Offline
datasets:
- name: products # the catalogue: downloaded, read-only on the device
direction: down
source: io.mateu.demo.fieldservice.Products
preload: wifiOnly
- name: work-orders # the technician's jobs: held, changed offline, synchronised
direction: both
source: io.mateu.demo.fieldservice.WorkOrders
conflicts: ask
keepFor: 7d
covers: [io.mateu.demo.fieldservice.WorkOrderLookup]
- name: inspections # written in the field, uploaded when back online
direction: up
source: io.mateu.demo.fieldservice.Inspections
fileFields: [photo]
screens:
- route: /workOrders
dataset: work-orders
- route: /inspections
dataset: inspections
- route: /products
dataset: products
  • source names what serves the dataset: an AutoCrud class (its store() serves it, see the default adapter), a SyncSource class, or a SyncSource bean by its class name or its simple name in lower camel case (productsSync).
  • screens are mount-relative routes, like every other route. A route reached from an @Menu field is /<field name> (/workOrders above).
  • mount (optional) names the app the file belongs to (mount: /field). Leave it out when the project has one mount. The datasets of one app never travel to another app’s devices.
  • Enum values are written in lower camel case: down | up | both, ask | serverWins | clientWins | mergeFields, always | wifiOnly | onDemand. The Java names (WIFI_ONLY) are read too.

The same list can be written in code, on the app class:

@UI("")
public class FieldApp implements OfflineManifestSupplier {
@Menu WorkOrders workOrders;
@Override
public OfflineManifest offline() {
return OfflineManifest.builder()
.dataset(OfflineManifest.Dataset.down("products", Products.class)
.preload(Preload.WIFI_ONLY))
.dataset(OfflineManifest.Dataset.both("work-orders", WorkOrders.class).keepFor("7d"))
.dataset(OfflineManifest.Dataset.up("inspections", Inspections.class)
.fileFields("photo"))
.screen("/workOrders", "work-orders")
.screen("/products", "products")
.screen("/inspections", "inspections")
.build();
}
}

A dataset can also be declared on its source, and a screen on its class:

@OfflineDataset(name = "work-orders", direction = SyncDirection.BOTH, keepFor = "7d")
@Service
public class WorkOrdersSync extends CrudStoreSyncSource<WorkOrder> {
public WorkOrdersSync(WorkOrderStore store) {
super(WorkOrder.class, store);
}
}
@Offline(dataset = "work-orders")
public class WorkOrders extends AutoCrud<WorkOrder> {
@Override
public CrudStore<WorkOrder> store() {
return Stores.WORK_ORDERS;
}
}

An @Offline class joins the manifest of the app whose @Menu reaches it (route /<field name>), or of the mount its own @UI route lives under. An OfflineDatasetSupplier bean declares datasets in code (OfflineDatasetDefinition records), the programmatic twin of @OfflineDataset.

Like routes and sources, the authored file wins. Datasets are merged by name, screens by route:

  1. specs/ui/offline.yaml (any type: Offline file whose mount is the app’s, or blank);
  2. the app class’s OfflineManifestSupplier;
  3. OfflineDatasetSupplier beans;
  4. @OfflineDataset beans (and @Offline screens).

When the app has an authored manifest (YAML or supplier), only its datasets travel, plus the derived ones that one of its screens names. The device asks the server for the resolved list for its caller, and downloads exactly that.

AttributeDefaultMeaning
name—the global, stable id. It is a storage key on every device that ever held it: keep it stable.
direction—DOWN, UP or BOTH.
key@PrimaryKey, else idthe record’s key field.
conflictsASKwhat a device does with a conflicting change (BOTH only). See Conflicts.
keepForno limithow long the copy stays usable without a successful pull: 7d, 12h, 30m or an ISO-8601 duration (PT12H). After it, the screens say the data is old.
refuseStalefalsea copy older than keepFor may no longer be edited.
keepAfterPushfalseUP only: keep a record on the device after the server accepted it.
wipeOnSignOutfalsesigning out deletes this copy (by default it is kept, locked).
maxRecords10000the most records the server sends one device. More are cut, with one WARN.
fileFieldsnoneUP/BOTH: the String fields holding files (photos). See Files and photos.
preloadALWAYSwhen a device downloads it (below).
coversnonerecord types or LookupOptionsSupplier classes whose lookups this dataset answers on the device.

The manifest is the preload list. On the first online open of the UI the device downloads every dataset its caller may hold, and caches the screens of every offline route. Each sync keeps them fresh. Nothing else is preloaded.

preloadWhen
ALWAYS (always)at the first online open, then at every sync
WIFI_ONLY (wifiOnly)only on an unmetered network: big catalogues, product images
ON_DEMAND (onDemand)the first time one of its screens is opened online: rarely used reference data

A SyncSource may answer estimate(rq) (a rough record count), so the phone can say “Ready for offline · 1 234 records” before it downloads.

An offline screen whose record has a @Lookup field (or a @RestOptions(source = X) field) needs those options on the device too, or the select is empty offline. Declare the referenced data as a DOWN (or BOTH) dataset that covers the lookup — covers names the @Lookup(search = …) class or the record type; for @RestOptions(source = X) the dataset is the one named X. In the demo, the work-orders dataset covers WorkOrderLookup, so an inspection’s work order is picked from the phone’s copy. Options an OptionsSupplier or an enum gives are sent with the screen and need no dataset.

Where the records come from and where the changes go is the app’s business, as with CrudStore or FileStorage. Mateu defines the port, the app implements it:

public interface SyncSource<T> {
Class<T> type();
SyncPage<T> pull(String cursor, int limit, HttpRequest httpRequest); // DOWN / BOTH
PushOutcome push(RecordChange<T> change, HttpRequest httpRequest); // UP / BOTH
Long estimate(HttpRequest httpRequest); // optional, default null
}
  • pull answers the changes the caller may see since cursor (null = everything), as a SyncPage(upserts, deletedKeys, nextCursor, more, resetRequired). The cursor is opaque to Mateu: a timestamp, a change sequence, a content hash — your choice. resetRequired tells the device to drop its copy and replace it with what follows (an expired cursor, a changed scope, a full page). SyncPage.full(records, cursor) and SyncPage.unchanged(cursor) cover the usual answers. To pull deletes incrementally, the server needs tombstones; without them, answer full pages.
  • push applies one change made on a device: a RecordChange(key, op, record, changedFields, baseVersion, madeAt, changeId), with op CREATE, UPDATE or DELETE. It answers a PushOutcome: accepted(newVersion, stored), rejected(message) (or a Rejected with field errors), or conflict(current, currentVersion) when someone changed the record since baseVersion. Your push may also merge a conflict itself and answer accepted.

Both calls run with the caller’s identity, like any request. So pull returns only that person’s records — their work orders, their region’s customers.

A source that pulls changes since a timestamp:

@OfflineDataset(name = "customers", direction = SyncDirection.DOWN, preload = Preload.WIFI_ONLY)
@Service
public class CustomersSync implements SyncSource<Customer> {
private final CustomerRepository repository;
public CustomersSync(CustomerRepository repository) {
this.repository = repository;
}
@Override
public Class<Customer> type() {
return Customer.class;
}
@Override
public SyncPage<Customer> pull(String cursor, int limit, HttpRequest httpRequest) {
if (cursor == null) {
return SyncPage.full(repository.findAll(), Instant.now().toString());
}
var since = Instant.parse(cursor);
return new SyncPage<>(
repository.changedSince(since),
repository.deletedKeysSince(since),
Instant.now().toString(),
false,
false);
}
}

CrudStoreSyncSource<T> (io.mateu.core.infra.offline) is a SyncSource over any CrudStore<T>. Zero code for the simple case, and what serves an AutoCrud class named as a manifest source:

  • pull answers the whole findAll() as one page the device replaces its copy with. The cursor is a hash of the content, so an unchanged set answers nothing. Fine for reference data up to a few thousand records; override pull for deltas.
  • push stores a create, lays an update’s changed fields over the stored record (fields the device could not write keep their stored values) and deletes — with the @Version check: a change made from an older version answers a conflict. An update of a record that is gone is rejected (“This record no longer exists.”); a create of a key already stored too (“A record with this key already exists.”); a delete of a record already gone is accepted.

A screen works offline when the manifest binds it to a dataset. Today that means:

  • AutoCrud screens, and capability listings (Listing with Navigable, Editable, Creatable, Deletable): the listing, search, filters, sort and paging, opening a record, creating, editing and deleting.
  • YAML pages with no view model (a routes.yaml entry with only a layout:), whose data comes from REST sources: see YAML pages offline.

While online, the server sends the device a pack for each offline route: the listing, the record page, the edit form and the create form as templates (the structure, never a real record’s values), the filters, the validation rules and which actions can run on the device. The pack is tied to the deployment’s build, so a new deployment refreshes it.

Online, the app keeps asking the server, as always. Only when a request fails because the device is offline (or the server does not answer in time) does the app answer it from the local copy:

On the screenOffline
search, filters, sort, pagethe local copy is queried with the same rules as online
open a record, its edit formthe template + the local record
New, then Savethe template; a new record with a key made on the device; a change in the log
Save on an editvalidation on the device, then a change (the changed fields + the version it was made from)
Deletehidden locally, a change in the log
any other action“Needs a connection”, or queued if it declares offline = QUEUE

A Java method with business logic cannot run on the phone, so a custom button on these screens, and any screen that is not bound to a dataset, keeps today’s behaviour: it needs a connection (or is queued, if it declares it).

A definition-only YAML page has no Java behind it: its listing reads rowsSource: {ref: parts}, its record page reads the route’s data: part, and its forms save through restActions. To take such a page offline, declare a dataset over those REST sources with rest: instead of source::

specs/ui/offline.yaml
type: Offline
datasets:
- name: parts
direction: both
key: id # the record's key field (default id)
rest: # names in sources.yaml
list: parts # the collection
record: part # one record: its url reads ${state.id}
create: part-create # leave a role out and that change is not possible offline
update: part-update
delete: part-delete
searchable: [code, name, category] # what free text searches on the phone (default: every field)
screens:
- route: /parts # the YAML route
dataset: parts

The code twin is OfflineManifest.Dataset.rest("parts", SyncDirection.BOTH, RestBinding.builder() .list("parts").record("part").create("part-create").update("part-update").delete("part-delete").build()).

On the server, nothing to write:

  • the pull calls list itself (like a proxied call: secrets, headers and a relative url resolve on the server) for page 0, 1, … while the source’s totalPath says more remain, and sends the whole set; the device replaces its copy each time it changed;
  • a push calls create, update or delete with the record as the state their url and body read. A 404 on an update is “This record no longer exists.” (on a delete: already gone, fine), another 4xx is rejected with what the service said, and a 5xx or no answer makes the phone keep the change and try again later. An object the endpoint answers is the stored record (its key wins: an endpoint that assigns its own ids is fine).

On the phone, while it has no connection (or the endpoint does not answer), the page’s calls of those sources are answered from the copy:

The page callsOffline
list (search, filters, sort, page)the copy, with the same search rules, answered in the endpoint’s own shape (itemsPath, totalPath)
recordthe record whose key is in the url’s ${state.id}
create / update / deletea change in the log, sent at the next sync; the page shows it at once

How the search is read: the listing resolves the source’s url with its state, and that state is what the phone searches with — searchText, page, size, sort, and every other ${state.x} the url (or body) names is a filter on field x. x_from / x_to are a range on x, a list value (a multi-select) means “any of these”, anything else is “contains” for text and “equals” for the rest. So name the url’s query parameters after the record’s fields (category=${state.category}), as the listing’s filters already are.

Limits of YAML pages offline: a REST dataset has no version, so there are no conflicts — the last change sent wins; the field errors an endpoint answers are not shown per field (its message is); a comma-separated value restored from a URL is a plain filter, not “any of”. The renderer side is one hook, registerRestSourceInterceptor (libs/mateu), that every catalogue call goes through; the phone registers the offline engine’s createOfflineRestInterceptor there. The demo demo/demo-field-service has a Parts catalogue built this way (specs/ui/parts*.yaml over the demo’s own /api/parts).

The device searches with the rules of CrudStore.find’s default: every word of the search text contained in the record’s text (any order, case-insensitive), contains for string filters, equality for the rest, range and multi-select criteria, nulls last ascending. One TypeScript implementation (libs/mateu) is held to a corpus written by the Java reference (conformance/client/offline-search.json).

If your store overrides find (a database query with other semantics), the online and offline results of the same search can differ. See also the ports below.

A record created on the phone gets its key on the phone: a UUID v7 (sortable, collision free). The server keeps it. Nothing is renumbered, so a later change of that record, or a child record pointing at it, needs no rewriting.

So a dataset whose records are created offline must have a UUID key: a String or UUID field. A dataset with a server-assigned key (a sequence, a code the user types) still works as DOWN, or as BOTH for editing only — it cannot create offline. Mateu says so at startup, once:

Offline dataset readings (…) cannot create records offline: its key is not a UUID (a String or UUID field)

A conflict happens in a BOTH dataset when the server’s version of the record is no longer the one the device edited. Give the record a @Version field: that is how the server tells.

conflictsWhat happens
ASK (default)the change waits under “Needs your attention”. The user opens it in a RecordMerge screen — theirs and mine, field by field — and the result is sent as a new change on the current version.
MERGE_FIELDSthree-way merge per field (base, mine, theirs): fields only one side changed are merged on their own. A field both sides changed falls back to ASK.
SERVER_WINSthe local change is dropped and the user is told: “Order 123 was changed by someone else; your change was not applied.”
CLIENT_WINSthe change is sent again, once, on the version the server answered.

The device sends changes in order, one at a time. A refused change (rejected) or a conflict waiting for the user stops the log there, because what follows may depend on it. Nothing is lost silently: a refused or conflicting change stays visible until the user decides (Try again, Edit, Discard, Resolve).

An UP or BOTH dataset lists in fileFields the String fields holding files — an inspection’s photo. The field is an ordinary file upload field, and the app registers a FileStorage, as for any upload:

public class Inspection implements Identifiable {
@Hidden String id;
@FileUpload(accept = "image/*", maxBytes = 10_000_000)
String photo;
@Override
public String id() {
return id;
}
}
  • Offline, the photo stays on the phone (the app’s documents folder). The record holds a local reference until it is synced.
  • At sync time, the phone asks an upload ticket (tickets live 8 hours, a phone may be offline for days, so it is asked then, not when the photo was taken), uploads the bytes through your FileStorage, writes the stored file’s value into the change, then sends it. A retry after a failure never uploads a file twice.
  • The server refuses a change whose file field holds anything but a stored file (or nothing): “This file has not been uploaded.”
  • A file too large or of a type the field does not accept makes the change rejected, with the reason on the field (“This file is too large.”, “This type of file is not accepted.”).
  • Without a FileStorage for the field, the ticket is refused: “Files cannot be uploaded here.”

Offline only delays the server’s verdict. It never replaces it.

  • What leaves the server: only what pull returns for the caller, minus every field the caller may not read (@EyesOnly fields never reach the phone, exactly as in a listing row), and at most maxRecords. A dataset whose source carries a class-level @EyesOnly the caller does not meet is not in their manifest at all.
  • Every push is checked again like an online save: the dataset’s direction (a DOWN dataset takes no push), the bound crud’s write gates (@ReadOnly, @Not*, canEdit()…), the fields the caller could not write online are dropped, and bean validation runs (a failure is rejected with “There are validation errors” and the field errors, and your push is never called). A modified app can only send what its user could have saved online.
  • Idempotent: each change carries its id as the Idempotency-Key, so a repeat (a lost answer, a retry) gets the first answer back and is never applied twice.
  • On the device: one encrypted database (SQLite with SQLCipher) per UI and per signed-in person. Its key is random, kept in the device keychain, usable only while the device is unlocked, and never leaves the device. Another person signing in on the same phone never sees the first one’s data.
  • Signing out locks the data: it stays on the device, untouched, until the same person signs in again, so pending work is not lost. A dataset with wipeOnSignOut is deleted instead; if it has changes not sent yet, the app warns before signing out.
  • Revocation: a pull or push answered with 403 for a dataset, or a manifest that no longer lists it, deletes that dataset’s copy. Its pending changes are kept for the user to see, never sent.
  • Removing the UI from the app’s list deletes its databases.
  • Server logs name datasets, ids and counts, never record values.
  • Sync indicator in the app bar: Synced, Syncing…, N pending or N need attention. It opens the Sync screen.
  • Sync screen: the changes waiting to be sent, in order; the ones that need attention — refused ones with the server’s message (Try again, Edit, Discard) and conflicts (Resolve opens the RecordMerge); the data on this device per dataset (“Ready for offline · 1 234 records”, “Last synced 2 h ago”, “Download (Wi-Fi)”); and Sync now. It replaces the send queue’s list.
  • Offline line: “Offline — your changes are kept on this device”, and “Offline — data from 2 h ago” when the copy is old.
  • Not synced marks on the listing rows and records changed here.
  • Needs a connection on actions that only the server can run.
  • First use: an offline screen never synced yet says “Connect once to download the data” instead of showing an empty list.
  • The hub row of the UI counts the changes pending and those that need attention.

The texts come in the app’s six chrome languages (English, Spanish, French, German, Portuguese, Italian).

When the connection comes back, when the app returns to the foreground, when the UI is opened, and on Sync now. Each sync pushes first (in log order) and then pulls every DOWN/BOTH dataset from its cursor, so the pull already reflects your changes. A server that fails, is busy or does not answer in time is tried again on its own (30 seconds, doubling up to 10 minutes). An expired sign-in asks the user to sign in again before anything is sent.

mateu-test simulates a device: what it downloads and what the server does with what it sends, with no phone and no browser. From the demo’s OfflineManifestTest:

import io.mateu.test.MateuTest;
class OfflineTest {
MateuTest mateu;
@BeforeEach
void start() {
mateu = MateuTest.builder().ui(Shell.class).start();
}
@AfterEach
void stop() {
mateu.close();
}
@Test
void aChangeMadeOfflineIsStoredAndAnOldCopyConflicts() {
var phone = mateu.device(Shell.class);
assertEquals(15, phone.pull("work-orders").size());
var id = Stores.uuid("work-order-3");
assertEquals("accepted", phone.update("work-orders", id, Map.of("status", "DONE"), 0).get("result"));
assertEquals("conflict", phone.update("work-orders", id, Map.of("notes", "x"), 0).get("result"));
}
}

mateu.device(app) (or device(app, identity) for a signed-in caller, e.g. Identity.withRoles("technician")) gives a Device with manifest(), pack(route), pull(dataset) (follows the cursor; copy(dataset) is what the pulls left), create, update, delete, push(...) (a change with your own changeId) and uploadTicket(dataset, field, count). Every answer is the wire JSON.

Mateu checks the resolved manifest when it is first built and warns once per problem. It never fails the startup:

WarningWhat to do
Offline dataset X (…) cannot create records offline: its key is not a UUIDuse a String/UUID key, or accept that the dataset is down / edit-only
Offline screen /r: the options of field (a lookup or a REST options source) come from no offline dataset, so they are empty without connectiondeclare a DOWN dataset that covers the lookup (or is named like the source)
Offline screen /r names the dataset X, which no producer declares: it is left outfix the name, or declare the dataset
Offline dataset X: its source answered N records, more than its maxRecords (M): the rest are not sentraise maxRecords, or narrow what pull returns

One page of a pull holds at most limit records (the device asks 500), capped by mateu.offline.max-page-size (1000; .NET and Python MATEU_OFFLINE_MAX_PAGE_SIZE).

Both ports implement the same protocol, read the same specs/ui/offline.yaml (or the directory in MATEU_SPECS_DIR) with the same precedence, and replay the same conformance scenario (conformance/offline/sync.json).

JavaC#Python
Declare a dataset@OfflineDataset(name, direction, …) on a SyncSource bean[OfflineDataset("name", SyncDirection.Both, KeepFor = "7d")] on an ISyncSource<T> class (parameterless constructor)@offline_dataset(name=…, direction=SyncDirection.BOTH, keep_for="7d") on a SyncSource subclass
Offline screen@Offline(dataset = "…")[Offline("…")]@offline(dataset="…")
The portSyncSource<T> (pull, push, estimate take the HttpRequest)ISyncSource<T> (Pull(cursor, limit), Push(change), Estimate())SyncSource (pull(cursor, limit), push(change), estimate(), record_type)
Default adapterCrudStoreSyncSource<T> over a CrudStore<T>CrudSyncSource<T> over a Crud<T>CrudSyncSource (mateu_ui.core.offline) over a Crud
Manifest in codeOfflineManifestSupplier.offline()IOfflineManifestSupplier.Offline()OfflineManifestSupplier.offline()
Datasets in codeOfflineDatasetSupplierIOfflineDatasetSupplierOfflineDatasetSupplier
OutcomesPushOutcome.accepted/rejected/conflictPushOutcome.Accept/Reject/ConflictingPushOutcome.accepted/rejected/conflict
[UI("work-orders"), Offline("work-orders")]
public class WorkOrders : Crud<WorkOrder>
{
public override IEnumerable<WorkOrder> Fetch(string? search) => Store.All();
public override void Save(WorkOrder entity) => Store.Put(entity);
public override void Delete(string id) => Store.Remove(id);
}
[OfflineDataset("work-orders", SyncDirection.Both, KeepFor = "7d")]
public class WorkOrdersSync() : CrudSyncSource<WorkOrder>(new WorkOrders());
from mateu_ui.core.offline import CrudSyncSource
@ui("work-orders")
@offline(dataset="work-orders")
class WorkOrders(Crud[WorkOrder]):
def fetch(self, search):
return store.all()
def get(self, id_):
return store.get(id_)
def save(self, entity):
store.put(entity)
def delete(self, id_):
store.remove(id_)
@offline_dataset(name="work-orders", direction=SyncDirection.BOTH, keep_for="7d")
class WorkOrdersSync(CrudSyncSource):
def __init__(self):
super().__init__(WorkOrders)
  • Where it works: the React Native app (hub and fixed builds), the web renderers Vaadin, Primer, SAP UI5 and Salesforce SLDS — the browser keeps an encrypted SQLite copy and opens the page with no network (Offline operation in the browser) — and the desktop app (Offline operation on the desktop). The Redwood renderer ignores the manifest and keeps working online only for now.
  • The web build of the React Native app (npm run web) keeps the offline copy in the browser’s localStorage, unencrypted. It is for development and demos only.
  • AutoCrud, capability listings and YAML pages over REST sources work offline. Custom forms and custom Java actions do not; their buttons need a connection or are queued. A REST dataset has no version, so its changes never conflict (the last one wins).
  • YAML datasets on .NET and Python: their servers do not read rest: yet (such a dataset is left out, with a warning) — use a Java server for YAML pages offline.
  • Row routes of a listing are not checked against the datasets at startup yet.
  • CrudStoreSyncSource pulls everything every time the content changed: fine for thousands of records, not for hundreds of thousands. Write a pull with a real cursor for those.
  • Offline search equals online search only with a Java server whose store keeps the default find (see above).