# Multiple Clients sharing data

When multiple client applications store data locally and share these with other application instances, data synchronization between different clients takes place. In order to support this case, a few fundamental considerations are necessary.

A *Client* is any application instance which stores data locally and which want to inform other instances about local changes as well as receiving updates from other instances. Each client instance that participates in the data exchange must have a unique `clientId`.

The `clientVersion` is a 64-bit integer that is used on the service to compare which Document is newer. If, for example, a client sent a Document with *clientVersion=1* and the corresponding Document on the service has already *clientVersion=2*, the update request is discarded. A good practice is to set clientVersion = milliseconds-since-epoch, on the client when the record is updated locally.

### Synchronization Workflow

1. Send local changes to the Service
2. Ask Service for changes from other clients since the last request.

#### Upload local changes

* The client collects all local records which have `localVersion > lastUploadClientVersion`, all documents which have been changed locally since the last upload.
* The client sends it local changes together with its `clientId` to the service: `POST Docs`,to update (upsert) all records on the Service. Don't forget to provide a `clientVersion` for each record!&#x20;
* The Service creates or updates all *Documents* on the service which do not exist or have a lower (or the same; in case clientVersion=0) `clientVersion`. The Service will also record the id of the client which sent the updates.
  * The Service sets the server date/time of the change in `LastUpdateUtc` .
* The client stores/updates `lastUploadClientVersion = max( localVersion)`, to remember the latest local change that was sent to the service.

#### Download server-side changes

* The client queries the Service for all changes since, which were not provided by the current client:  `POST /Docs/Query?origin=other&sinceUtc=${sinceUtc}`
  * The Services responds all Documents with `LastUpdateUtc ≥ sinceUtc` where `clientId` which provided the Document is different from the querying clientId, to avoid infinitive loops (sending the same record forth and back).

> The querying client cannot know about `clientVersion`s which have been provided by other clients, and that is why `clientVersion` is not suitable to query changes. To query changes the server-site `LastUpdateUtc` is the information to rely on.

* The client records `newestKnownServiceRecordUtc = max( LastUpdateUtc)` to be able to start the next request with an appropriate date.
* The client updates its local database.
* The client does not process the incoming clientId, because it is not of interest which client updated the record.&#x20;
* The client sets `localRecord.clientVersion = serviceRecord.clientVersion`.&#x20;
