Rolando Andrade
Back to Content

Creating Offline-First Applications

How offline first web apps work: local data, optimistic updates, sync with Pusher, Replicache push and pull strategies and causal consistency, using Bezier.

· 7 min read
Creating Offline-First Applications

Imagine you are writing in Google Docs and your connection drops. Now imagine the app stops working until the internet comes back. Offline first applications exist so that never happens. They are web applications that feel like local apps. They respond right away, even with a slow network or no network at all.

Over the last few years, this approach has become popular. I have been using it to build Bezier, a tool for writing system documentation. After months of working with it, I want to share how this type of system works.

How most apps work today

Most web applications follow a client server architecture. The user works with a page in the browser, the client. The page sends calls to an external server for some operations, like storing data in a database or processing something.

Client Server Architecture
Client Server Architecture

This architecture has shaped application design for a long time. Almost every web application you use today follows some version of it. So do many desktop and mobile apps.

Because the parts live on different machines, this approach has the usual problems of distributed systems. The main ones are latency, data consistency and keeping the system up.

Latency makes users wait

Latency is the time a message takes to travel from one place to another. Think about registering a user. The browser sends a request to the server, the server sends it to the database, and then the response travels back. Most of the time in those requests is not processing. It is latency. That is why requests on localhost, your own machine, feel instant. In remote environments, we wait 100 to 500ms for each response.

To show this waiting time, developers usually block the UI and show a loader. It tells the user that something is happening. When the response arrives, the loader stops and the user can continue.

Loader animation
Loader animation

Shared data can break

Now imagine two clients editing the same data, like a filesystem. User A deletes the file foo.txt, but user B does not see the change. Now the system is not reliable. If user B tries to open the deleted file, they will probably get an error.

This type of error is about the consistency and integrity of the data. To handle it, developers usually build integrity services and use heavy, reliable infrastructure.

Offline means broken

Now imagine the application goes offline. It just stops working. Most of the time, developers show a message like Something went wrong. Try again later, and the user cannot continue.

Can you imagine not being able to use Google Docs just because you lost connection? It would be awful. Writing is something a device can do offline. So why not let the client handle the writing instead of the server?

The offline first idea

Offline first applications solve most of these distributed system problems. The price is more complexity in the data layer and the backend services.

The idea is to remove the dependency on the server. The application stores every mutation (every change) locally and keeps working. It sends the changes as soon as the server is available again.

Offline First Architecture
Offline First Architecture

Bezier as an example

An example makes this easier to explain, so let’s use my application, Bezier. It is a tool for writing beautiful documentation and design systems with diagrams.

What happens in the browser

The first time a user opens the workspace, the client downloads the website from the server. Then it runs scripts that save the data locally in the browser. From that moment, the main database for the client is the browser’s IndexedDB, a database built into every modern browser. The frontend reads all its data from there.

When the user makes a change, for example creating a new project (a Story), the change triggers a mutator. A mutator is a service that writes to the local database and adds the mutation to a queue in a sync service. It performs an optimistic update.

An optimistic update applies the change without waiting for the server’s answer. So the project appears for the user right away. The user can work with it while the backend processes the request, or even before the backend receives it!

Optimistic UI Diagram
Optimistic UI Diagram

The sync service has three parts:

  1. A polling service asks the server for new data every X seconds.
  2. A message service receives messages from tools like Pusher. These tell it about changes from other clients in real time.
  3. A push service sends all the queued mutations to the server.
The three parts of the sync service in Bezier
The three parts of the sync service in Bezier

Say a team member is in the same workspace at that moment. If they are online, they receive a real time Pusher event. Their sync service updates their local database and refreshes the view. The frontend reads from the local database, so it shows the new project. If the team member is offline, nothing is lost. When they come back online, the polling service gets the changes from the server. It updates the local database and refreshes the view.

What happens on the server

This architecture has a drawback. The backend services depend heavily on the sync service. You can keep the business services separate, but the data model needs some new fields. Also, most updates must go through one controller instead of different endpoints, because every client polls that endpoint every X seconds.

There are four main strategies to pull and push data in this approach: Reset, Global Version, Per-Space and Row Version. You can learn more about them in the documentation of Replicache. I will write more articles about them in the future. For now, here is a short description of each one:

  • Reset Strategy: It works like a PUT operation. Every time a client makes a change, it pushes everything to the database and replaces all the resources with a new version. Other clients also pull everything. It wastes resources, but it is very easy to build.
  • Global Version Strategy: Each entity that can change gets a version field. After a change, the version goes up by one. Every client syncs its data from the last version it saw. All data goes to all users, so you cannot have private workspaces or channels.
  • Per-Space Strategy: On top of the version field, each resource gets a field that names its workspace. If a user in workspace W makes a change, users in workspace X do not pull it, because changes are filtered by space.
  • Row Version Strategy: It uses Client View Records (CVRs). A CVR holds all the data a client can see at a given time. To find what changed, you compare the last CVR with the new one.

For Bezier, I used the Per-Space Strategy. It fit the task best, and it is simple. The implementation looks roughly like this:

Pushing Data

  • Verify the client belongs to the workspace.
  • Increase the mutation version for the client (changes made by the client) and for the client group.
  • Add the mutation and increase by one the mutation version for that resource and workspace.
  • Call the message service (Pusher) to notify every subscribed client of the change.

Pulling Data

  • The client sends a pull request with its current version (changes made by the client).
  • Verify the client belongs to the workspace.
  • Get every record of that space with a version greater than the current version.
  • The client updates its data and its current version.

We will look at this in more depth in future posts. For now, it is a good introduction. It shows how to manage versions of a resource that many clients share.

When two edits collide

You may be wondering about conflicts. Every system has them, and this one is no exception. There are many consistency models. Causal Consistency is one of the strongest. It is the approach of Replicache, the library I used in Bezier and the reference for this post.

Causal Consistency Causal Consistency - Causal consistency is a model that guarantees that operations that are logically connected will be observed in the same sequence by all processes within a system. jepsen.io

Causal consistency guarantees one thing. When operations are logically connected, every process in the system sees them in the same order. So if one operation depends on another, everyone sees them in the right order.

Here is an example:

  • User A creates a document called “Document 1” and adds a few points.
  • User B also creates a document called “Document 1” and adds different points. A and B did the same operation. The system sees that one is redundant and updates the local copy with the one created on the server.
  • User A and User B both edit their documents offline.
  • When the devices reconnect, the app uses causal consistency to find the correct order of operations and merge the changes.
  • The final document may include both sets of points, or remove one.

The key is to have only two atomic operations, put and delete. Atomic means each one fully happens or does not happen at all. This makes operations easy to merge. They can also be ordered in time by their dependencies when the version field cannot tell which mutation came first.

Push, pull and consistency next

Today we learned the basics of how offline first applications work, and some key ideas for their design. In future posts, I will go deeper into the strategies to push and pull data. I will also explain more theory about consistency models in distributed systems.

For now, have a great week, and see you in the next posts!


If you enjoy the content, please don’t hesitate to subscribe and leave a comment! I would love to connect with you and hear your thoughts on the topics I cover.

Interested in working together? Check out my services and pricing to see how we can collaborate on your next project. Let's Build