Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Created February 26, 2019 08:37
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pesterhazy/a840a21000b67cc5b7e601fdc91b9e18 to your computer and use it in GitHub Desktop.
Save pesterhazy/a840a21000b67cc5b7e601fdc91b9e18 to your computer and use it in GitHub Desktop.
Offline-first browser apps and multiple tabs

Offline-first browser apps and multiple tabs

For offline-first operation, browser apps cache data in an IndexedDb database. When the user makes a change while offline, they persist the change optimistically. When connectivity is restored, changes are synced to the server.

This pattern is well established today. However, given the possibility of opening the app in multiple tabs at the same time, we seem to be faced with a dilemma:

  • We allow users to use the app and to make changes in multiple tabs at the same time. But then two "threads" are writing to the same shared resource at the same time. Co-ordinating writes seems to be difficult.

    To make things worse, while the localStorage API allows you to register a callback that fires whenever an item is changed outside the current tab, the IndexedDb API doesn't, at least not in a widely-available way.

  • Alternatively, we can disallow changes to the database from multiple tabs at the same time. This seems safer and less complex. However, the user experience is not ideal: the user would see a message "this resource is being used in another tab at this moment" or similar. Additionally, given the lack of API support, the locking logic is not trivial to implement either.

So what is the best way to deal with this issue? I haven't found a satisfactory answer for now so I'm curious how people deal with offline-first apps in multiple tabs. Please leave a comment if you have experience with this issue.

For completeness, another alternative might be to release all resources like IndexedDb DB handles whenever the user switches away from the current tab, and to open the DB again when the tab gains focus again. But this seems more like a workaround than a proper solution.

@pesterhazy
Copy link
Author

Relevant issue in Cloud Firestore

@pesterhazy
Copy link
Author

More on Firestore here

@pesterhazy
Copy link
Author

There's the Page Visiblity API for determining if the current tab is active or hidden

@pesterhazy
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment