Sync and Offline
The browser keeps its own copy of the entities its user may read, and pages read from that copy. Hologram fills it, keeps it current and saves it in the browser, and it sends the writes the user makes, whether the server is reachable or not. None of this needs code from the app, but if users work offline, check how long your session cookie lasts, as Keeping Users Signed In below describes. This page covers what happens along the way, so you know what users see when the network drops, the server restarts or someone signs out.
How Sync Works
Each tab already has a stream from the server for realtime updates, and sync uses the same stream, with no connection or endpoint of its own. The server sends every entity the user may read, of each entity type the browser code reads, as Reading Data describes. It checks each entity against the access rules before it sends it, and an entity the user may not read never reaches the browser, not even as a sign that it exists.
A lazy entity type, declared with sync_mode: :lazy, never arrives whole. The browser gets only the entities its fields load, the ones it created itself, and the signed-in user's own entity when the user type is lazy. Those follow the rest of this page, with the differences described under Lazy Entity Types below.
The entity types the current page reads come first, including those of a panel that opens only on a click, and the rest follow. Once a type that isn't lazy has arrived whole, a page can answer any query over it without asking the server. The first render doesn't wait for any of this. The HTML the server renders carries the entities the page's queries returned, so the page's live reads give the same results in the browser from the start. A page that opens while another tab of the app is open can show older values until that tab has caught up with the server.
First Load, Catch-Up, Full Refill
On a user's first visit, the server sends all of it. The browser saves the entities in IndexedDB as they arrive, together with how far it has got. When the tab reloads, or the stream drops and comes back, the browser shows what it saved and tells the server where it stopped, and the server sends only what changed since then. That's a catch-up, and it costs what changed, not what the browser holds.
Sometimes the server sends everything again instead. That's a full refill, and it happens when:
- more than 5,000 entities changed since the browser stopped, past which a refill costs about the same as a catch-up
- a deploy changed the access rules, so what the user may read could have changed too
- a deploy changed the data model, like an added attribute or a new entity type, or changed which entity types reach the browser or an entity type's
sync_mode - the database lost track of where the browser stopped, like after a restore from a backup
- the app turned on
rebuild_local_databases, described under Rebuilding Local Databases below
A deploy that changes only pages, components, actions or commands doesn't force one, so browsers coming back after it catch up.
During a refill the page keeps showing what the browser holds, and the user can keep reading and writing. Once the refill ends, the browser drops the entities the server didn't send again, which are the ones deleted while it was away and the ones the user may no longer read. Writes the browser hasn't sent yet stay, and go to the server as usual. A grant or a revoke made while the browser was away doesn't force a refill. The catch-up adds the entities the user may read now and removes the ones they may no longer read.
A deploy or a server restart closes every stream at once, and nearly every browser comes back within seconds. Each server lets them catch up four at a time, in the order they came back. Meanwhile, every page keeps working from what its browser holds.
The server sends a catch-up in pieces of 500 entities, so a browser cut off during one picks up after the last piece it got.
Sync needs no configuration to work. Each server opens its own database connections for first loads and catch-ups, apart from the app's own pool, so a crowd of returning browsers doesn't slow the app's requests. There are 4 of them by default, and pool_size under :sync changes that:
config :hologram, :sync, pool_size: 4
pool_size takes a positive number, so the smallest pool is 1. Count these connections against the database's connection limit. Deploying lists all the connections a server opens.
Hologram reads the :sync settings when the app boots, so they work from config/runtime.exs too.
Rebuilding Local Databases
The entities saved in browsers can go wrong because of a mistake on the server, like a bug in a release that's since been fixed, or rows changed outside Hologram. A catch-up doesn't repair them, since it sends only the changes Hologram recorded. To have every browser replace what it saved, set rebuild_local_databases under :sync:
config :hologram, :sync, rebuild_local_databases: true
The option takes effect when a server boots. Each browser does one full refill the next time it connects. Writes it hasn't sent yet stay, and go to the server as usual. Every browser downloads everything again, so expect the traffic and the database load that come with that, mostly right after the deploy, when the open tabs reconnect.
If the mistake was a bug in the code, deploy the fix first and turn the option on in a later deploy. Otherwise, servers still running the old code during the deploy can send wrong entities to browsers that were already rebuilt.
Later restarts and deploys with the option on don't start another rebuild, and you can remove it any time. A browser that was away still rebuilds when it comes back. To rebuild again, turn the option off for one deploy and on again in the next.
Turn it on on every server. If one boots without it after another booted with it, the next one to boot with it starts a new rebuild, and browsers can download everything once more.
Lazy Entity Types
Reading Data covers declaring a lazy type and reading it. The browser saves the lazy entities it holds in IndexedDB too. When it reconnects, the server checks them again, updates the ones that changed, and removes the ones deleted or no longer readable. Each open query is answered again, so lists and totals catch up.
Tabs share lazy queries through the leading tab. Signing in or out drops the lazy entities and closes the queries.
When the connection is down, a field that has an answer keeps it, and a field that needs a new one isn't ready. Going back to a recent query works offline while the page stays open. The user's own writes show in a list or a single entity where the entities the browser holds are enough to tell the result. Otherwise, and for a count, they show once the connection is back and the server has answered.
Changing a type's mode in a deploy shows open tabs the reload notice, and browsers do a full refill. A type that becomes lazy loses the entities saved for it.
After a deploy that changed the data model, the server keeps answering the lazy queries of the tabs opened before it, as long as those tabs can keep syncing. It refuses the ones it can't answer for such a tab, like one whose field now builds a different query, or one that filters or sorts by an attribute the deploy deleted. The field keeps its last answer, and the tab shows the notice. Deploys and Open Tabs below covers the rest.
Live Updates
Every write through the data layer, by a user, a command or a job, reaches every browser that holds the entity or may read it now. For a lazy type, it reaches the browsers that hold the entity or have a query open that it changes. Each server watches the database for new writes, checks each one against the access rules of every user with an open tab on that server, and sends each browser what changed of what it may read. An entity a write makes readable arrives whole, and one it makes unreadable is removed from the browser. Servers learn about each other's writes from the database, not from each other. They still have to be connected in a cluster, for opening the stream and for lazy queries, as Deploying describes.
A write that skips the data layer never reaches the browsers, which is why DB.sql runs read-only. The same goes for a row changed with psql or another tool straight in the database, which leaves browsers out of date with no error anywhere. Rebuilding Local Databases above covers repairing them.
A role works the same way. When a user is granted a role on a project, the project's entities they may now read arrive in their open tabs, and when the role is revoked, those entities leave. Roles covers granting and revoking.
Deploys and Open Tabs
A tab opened before a deploy keeps running the code it loaded. When the deploy changed only the access rules, the tab gets the new rules when it reconnects and uses them from its next render, with nothing lost. Access Control covers what a tab checks until they arrive.
When the deploy changed the data model, the tab keeps syncing if the server can still give it entities in the shape it knows. It can after additions and renames, and after most other changes when the migration says with old_clients_get: what such tabs get. The tab doesn't get what's new, and an entity the old code has no way to show, like one with a new enum value, is missing there. Migrations lists what happens for each change.
After any other change, like an attribute deleted without old_clients_get:, the tab shows a notice asking the user to reload. Hologram doesn't reload the page for this, and until the user reloads, the tab keeps showing what it holds. The next page the user opens loads fresh from the server.
A tab running the old code can write, whether it keeps syncing or shows the notice. The server changes its writes to fit the current data model, like renaming an attribute or filling in a new required one from the migration, then checks them by the current rules.
Values the tab got through old_clients_get: need more care when they come back:
- A value sent back unchanged is left alone. A form that saves all its fields doesn't overwrite the real status with the older one the tab was shown. The other side of this is that picking the value the tab already shows changes nothing.
- An edit of a value that moved to another entity is saved there. This works when
old_clients_get:is a path to the new place, likeclient.name, and a migration's backfill copied the value there unchanged. A copy made by a job or a script doesn't count. The access rules of the other entity apply, and if they refuse the edit, the server refuses the whole batch. - When a to-one relationship became a to-many one, picking another entity in the old tab removes the link it had and adds the new one. If the entity then has several links, the tab shows the one
old_clients_get:names, which may not be the one the user picked.
A value with nowhere to go, like an edit of an attribute the deploy deleted, is left out. The server applies the rest and logs a warning, and a tab that edited an entity goes back to the value it had before. An app can't see in the browser what was left out yet.
The server refuses the batch when it can't fill in a required value or convert a value to an attribute's new type. It also refuses one that creates or updates an entity of a deleted type, sets a deleted enum value, or grants a deleted role.
Sometimes the server can't tell from its migrations what the tab's writes mean, like after a rollback to code that doesn't know the tab's data model. Then the tab shows the notice and holds its writes, on screen and in the queue, until the user reloads.
Writes can still be in the queue when a page loads the new code, like the ones made offline or the ones a tab held. That page sends them, unless a tab on the old code is still open to send them itself. The writes leave the screen at the reload and come back through sync once the server has applied them. If the server refuses a batch, its writes don't come back, and the browser prints a warning in the console. If the server still can't tell what the writes mean, the browser prints a warning and keeps them in the queue, and the next page load tries again.
The browser deletes what it saved for the old data model once none of its writes are waiting and no tab has it open. Writes of a user who signed out count too, and they wait until that user signs in again.
A data model change also costs every browser one full refill.
Keeping Users Signed In
By default, the session cookie of a Phoenix app lasts until the browser closes. A user who makes changes offline, closes the browser and comes back later is then signed out. The browser drops the entities it saved for them, and the writes it hasn't sent yet wait until they sign in again in that browser.
If your users work offline, give the cookie a lifetime with max_age, in seconds, in the session options in endpoint.ex. This one lasts 30 days:
@session_options [
store: :cookie,
key: "_my_app_key",
signing_salt: "...",
same_site: "Lax",
max_age: 60 * 60 * 24 * 30
]
The user then comes back signed in, and their writes go out once the app is open and connected. The time counts from the last change to the session, which is often the sign-in, and a visit alone doesn't extend it. Pick a lifetime longer than your users stay away.
The price is that on a shared device, the next person to open the browser is still signed in as the last one, unless that person signed out. Leave max_age out if your app runs on shared devices.
Offline Writes and Retries
An open tab keeps working offline. Live reads answer from what the browser holds, writes show up at once, and the batch each action makes waits in a queue in IndexedDB, so closing the tab or the browser doesn't lose it. It goes out the next time the app is open with the same user signed in. Reads of lazy types differ, as Lazy Entity Types above describes. Opening, reloading or navigating to a page still needs the server, since a page loads from it.
Batches go to the server one at a time, in the order they were made. When one gets no answer, because the network is down, the server timed out or it answered with an error, it stays in the queue and the batches behind it wait. The browser sends it again on the next write, when the connection comes back, or after a pause that grows from a quarter of a second to five seconds. A send gets 30 seconds, plus one second for each 4,000 bytes, so a big batch has time to upload on a slow connection. Sending a batch twice never applies it twice. When the server applied a batch but its answer got lost, the second send gets the same answer. A refused batch gets the same refusal too, unless it was a visitor's or was refused for its clock. The server doesn't record those two refusals, so it judges the batch again, and the second send can be applied.
Apart from the writes kept after a deploy because the server can't tell what they mean, a batch the server refuses is final. The browser undoes its writes, as Writing Data describes, and doesn't send it again. A refusal comes from the server checking the batch, or from a proxy that finds it too big, never from a send that didn't get through.
Hologram stops a batch that gets too big in the action that makes it, as Writing Data describes, so only a proxy in front of the app with a lower limit refuses one for its size. When the proxy answers 413, the browser drops the batch, undoes its writes and doesn't store a copy. The app isn't told yet. The batches behind it go. A proxy that cuts the connection instead looks like being offline, so the batch stays in the queue and the ones behind it wait.
To avoid both, let request bodies of at least 8,064,000 bytes through to /hologram/mutation. That's 8,000,000 for the writes and 64,000 for the rest of the request. nginx allows 1 MB by default, and client_max_body_size raises it. The request body limit in the app's own endpoint doesn't apply to this path. Hologram reads the body itself, so the browser sends it without a Content-Type header, which makes Plug.Parsers leave it unread. Nothing in front of the app may add that header. The app's parsers would read the body first, and no batch would get through.
Writes can wait offline for days, with no limit on how many or how long. What can end them is the browser clearing the site's storage, which Safari does to a site not visited for seven days. Hologram asks the browser to keep the storage when the browser allows that without asking the user, and an app the user installed to the home screen keeps its storage.
An app can't see the queue yet. There's no way to show how many writes are waiting, whether the browser is connected, or that the server refused a batch.
Clock Allowance
Each write in the browser carries the time it was made, from the browser's clock, and that's the time Writing Data uses to settle conflicts. The browser never gives a write an earlier time than one it has already seen, even across reloads, so a clock set back doesn't reorder a user's own edits.
A clock that runs behind is accepted, but its edits look older than they are, so they lose more conflicts. A clock that runs ahead would win conflicts it shouldn't, so the server refuses a batch whose time is more than five minutes ahead of its own, and the browser undoes it. Five minutes covers a device whose clock isn't synced, and a clock within it can win a conflict unfairly by at most that long.
Tabs and the Leading Tab
Tabs of one app in one browser share the entities in IndexedDB and the write queue. One of them leads. It holds the sync stream, passes what arrives to the other tabs, and sends the writes of every tab, so a browser makes one sync connection however many tabs are open. When the leading tab closes or crashes, the tab that has waited longest takes over, with nothing lost.
A browser that lacks the APIs tabs need to coordinate, Web Locks and BroadcastChannel, lets each tab sync on its own.
Sign-In, Sign-Out and Tabs
The entities a browser holds belong to the user signed in. When someone signs in or out, in any tab, every open tab of the app switches together. Each drops the entities it holds and fills again for the new user, or for a visitor after a sign-out.
A write belongs to whoever was signed in when the action made it, and the server applies a batch only for that user. So when the user changes, the writes the previous one hadn't sent yet leave the screen and wait in the queue. They go to the server the next time that user is signed in to the same browser. A visitor's writes count as the visitor's too, so writes made before signing in don't move to the account.
If someone signs in or out while another command is running, the browser drops the actions that command sends back, including its own broadcasts to that tab, and prints a warning in the console. They were made for the previous user.
Browsers Without IndexedDB
This is rare. Every current browser has IndexedDB, in private windows too. It's missing in the private windows of some old browsers, or when the user blocks it, for example by blocking all cookies. Without it, the browser keeps the entities and the write queue in memory. The app works the same while the tab is open, offline too, but a reload starts from nothing, and writes the server hasn't received are lost when the tab closes. Each tab syncs on its own. The same happens in any browser when IndexedDB stops working partway, like when the disk fills up, from then until the tab reloads.
A private window has IndexedDB, but the browser deletes what it saved when private browsing ends, including writes the server hasn't received.