Making web applications useful when the backend is unavailable.

Introduction: Loading Offline Is Only the Beginning

In Part 1, we explored the challenges of building web applications for unreliable networks and low-bandwidth environments.

We discussed bandwidth, latency, browser storage, Service Workers, the Cache API, and how to make an application's shell available offline.

By the end, our Resilient Task Board could load its application shell after it had been installed and its required resources cached.

But there was still a problem.

The application could open offline, but could it actually do anything useful?

Imagine opening a task management application without an internet connection. The interface loads successfully, but your tasks are missing because the application still depends on an API request to retrieve them.

You try creating a task, and the request fails because the backend is unreachable.

We have improved availability, but we haven't solved data availability or offline interaction.

This is where the next layer of resilience begins.

1. Understanding the Difference Between Application Availability and Data Availability

An application can be available without its data being available.

Consider these two scenarios:

  • Application availability: The user can open the application, navigate its interface, and access its basic structure.
  • Data availability: The user can access relevant information even when the backend cannot be reached.

Caching HTML, CSS, and JavaScript helps with the first problem. It does not automatically solve the second.

For our Task Board, we need a way to store and retrieve tasks locally.

That brings us to IndexedDB.

2. IndexedDB: Giving the Browser a Local Database

In Part 1, we introduced three important browser storage technologies:

  • LocalStorage
  • Cache API
  • IndexedDB

Each serves a different purpose.

LocalStorage is useful for simple key-value data such as preferences. The Cache API is designed to store network requests and responses. IndexedDB, however, gives us a structured, asynchronous database inside the browser.

It can store JavaScript objects, create indexes, and support transactions.

For our Task Board, this makes IndexedDB a suitable place to store task records locally.

Think of it as a database available to the application even when the network is unavailable.

Why not LocalStorage?

Although LocalStorage can store serialized objects using JSON, it is synchronous and does not provide the structured querying, indexing, and transaction capabilities we need for a more substantial offline data layer.

IndexedDB is better suited to this job.

Designing our local data store

Our application already has a Task type. We can use that model to define the records stored locally.

For example:

export interface Task { id: number; title: string; description?: string; completed: boolean; } 

We can create an IndexedDB database and an object store for tasks.

const DB_NAME = "resilient-task-board"; const DB_VERSION = 1; const TASK_STORE = "tasks"; export function openDatabase(): Promise<IDBDatabase> { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onupgradeneeded = (event) => { const db = (event.target as IDBOpenDBRequest).result; if (!db.objectStoreNames.contains(TASK_STORE)) { db.createObjectStore(TASK_STORE, { keyPath: "id", autoIncrement: true, }); } }; request.onsuccess = () => { resolve(request.result); }; request.onerror = () => { reject(request.error); }; }); } 

A few things are happening here:

  • indexedDB.open() opens or creates the database.
  • DB_VERSION allows us to manage future database schema changes.
  • onupgradeneeded runs when the database is first created or its version changes.
  • createObjectStore() creates the equivalent of a collection or table for our task records.
  • keyPath tells IndexedDB which property identifies each record.

We now have a local database to work with.

Saving and retrieving tasks

Once the database is open, we can perform operations through transactions.

For example, retrieving all locally stored tasks:

export const getTasks = async (): Promise<Task[]> => { const db = await openDatabase(); return new Promise((resolve, reject) => { const transaction = db.transaction(TASK_STORE, "readonly"); const store = transaction.objectStore(TASK_STORE); const request = store.getAll(); transaction.oncomplete = () => { db.close(); resolve(request.result); }; transaction.onerror = () => { db.close(); reject(transaction.error); }; transaction.onabort = () => { db.close(); reject(transaction.error ?? new Error("Transaction aborted")); }; }); }; 

Notice that we resolve the operation when the transaction completes, rather than assuming that an individual request succeeding means the entire transaction has committed.

That distinction matters when working with IndexedDB.

We can also save a task using a readwrite transaction and the object store's add() or put() method.

The important idea is that our application now has a local source from which it can retrieve data without depending on a network request.

3. Local-First Reads: Read From the Browser Before the Backend

Now that we have a local database, how should the application retrieve its tasks?

One approach is to always request data from the backend first and use IndexedDB only when the request fails.

But this still makes the user wait for the network whenever it is slow.

A better approach for our Task Board is a local-first read strategy.

The application reads from IndexedDB immediately, renders the available data, and then attempts to retrieve the latest data from the backend when connectivity is available.

The flow looks like this:

  1. The application requests tasks.
  2. It retrieves locally stored tasks from IndexedDB.
  3. The interface renders those tasks.
  4. It attempts to fetch the latest tasks from the backend.
  5. If the request succeeds, the local database is updated.
  6. The interface reflects the refreshed data.

This gives users a faster initial experience and allows them to see previously saved tasks even when offline.

There is an important distinction here: local-first does not mean the local database is always the source of truth.

In our architecture, MySQL remains the authoritative shared database. IndexedDB is the local copy used to support availability and interaction.

The two databases have different responsibilities.

Database Responsibility
MySQL Authoritative shared application data
IndexedDB Local data available to the current browser

This distinction becomes especially important when multiple users access the same application.

4. Offline Mutations: What Happens When Users Change Data?

Reading data offline is one challenge. Changing data offline is another.

Imagine a user creates a task while disconnected.

The browser cannot reach the backend, so the API request fails.

Should we simply display an error and ask the user to try again later?

That would mean the application is technically available offline but still not very useful.

Instead, we can allow the user to perform the operation locally and synchronize it with the backend when connectivity returns.

This is called offline mutation handling.

For example, when a user creates a task:

  1. Generate a unique identifier for the operation and a local identifier for the task.
  2. Save the task locally in IndexedDB.
  3. Record the operation as pending synchronization.
  4. Update the interface immediately.
  5. Attempt synchronization when the backend becomes reachable.
  6. Mark the operation as synchronized once the server confirms it.

The user does not have to wait for the backend before seeing the task appear.

Optimistic UI

This approach is closely related to a technique called optimistic UI.

Optimistic UI updates the interface before receiving confirmation from the server, based on the expectation that the operation will succeed.

For example, when a user marks a task as completed, the interface can immediately display it as completed.

But what if the request fails?

The application must have a recovery strategy. Depending on the operation and the application's data model, it can retain the pending change for retry or roll back the optimistic update.

Optimistic UI improves perceived responsiveness, but it does not guarantee that the server has accepted the change.

That distinction should never be ignored.

5. Building an Offline Mutation Queue

If users can perform several operations while offline, we need a reliable way to keep track of them.

This is where an offline mutation queue becomes useful.

Rather than sending an operation and forgetting about it when the request fails, we store it locally until the backend confirms that it has been processed.

A queue record might look like this:

interface PendingOperation { id: string; type: "CREATE_TASK" | "UPDATE_TASK" | "DELETE_TASK"; payload: Record<string, unknown>; status: "pending" | "syncing" | "failed"; createdAt: number; retryCount: number; } 

Each operation contains enough information for the application to attempt it again later.

For example, creating a task offline might produce this record:

const operation: PendingOperation = { id: crypto.randomUUID(), type: "CREATE_TASK", payload: { title: "Prepare workshop article", completed: false, }, status: "pending", createdAt: Date.now(), retryCount: 0, }; 

The operation is stored in IndexedDB alongside the locally available task data.

When connectivity returns, the application can process pending operations and send them to the backend.

A simplified synchronization flow looks like this:

User performs an action | v Save change locally | v Add operation to queue | v Is backend reachable? | +---+---+ | | Yes No | | v v Send API Keep operation request pending | v Server confirms? | +---+---+ | | Yes No | | v v Mark as Keep for synced retry/recovery 

This gives us a controlled way to handle changes that cannot immediately reach the backend.

However, simply retrying every failed operation introduces another problem.

6. The Idempotency Problem: What If the Server Already Processed the Request?

Consider this scenario:

  1. A user creates a task.
  2. The browser sends the request.
  3. The backend creates the task successfully.
  4. The response gets lost because the network drops.
  5. The browser assumes the request failed.
  6. The application retries the request.

What happens?

Without additional protection, the backend may create the same task twice.

This is a classic distributed-systems problem: the client does not always know whether the server completed an operation when communication fails.

One solution is idempotency.

An operation is idempotent when repeating it produces the same intended result as performing it once.

For mutation requests, we can use an idempotency key: a unique identifier generated by the client and sent with the request.

For example:

POST /api/tasks Idempotency-Key: 7c8f5d1a-... Content-Type: application/json 

The backend records the key and the result of processing the request.

If it receives the same key again, it can return the previously recorded result instead of creating another task.

This requires backend support. Generating an idempotency key in the browser alone does not prevent duplicate operations.

Retries without idempotency can create more problems than they solve.

7. Retry Strategies: Don't Attack the Backend

When a request fails, immediately retrying it repeatedly is usually a bad idea.

Imagine thousands of users reconnecting after a network outage and all their applications sending requests simultaneously.

The backend could become overwhelmed.

A better approach is to use exponential backoff.

Instead of retrying at fixed, very short intervals, the application progressively increases the delay between attempts.

For example:

Attempt Delay
1 1 second
2 2 seconds
3 4 seconds
4 8 seconds
5 16 seconds

In production systems, random jitter is often added to these delays to prevent many clients from retrying at exactly the same time.

We should also distinguish between temporary failures and permanent failures.

A temporary network error may justify another attempt. A validation error, such as an invalid task title, will not be fixed by repeatedly sending the same request.

Retries should be intentional, bounded, and based on the type of failure.

8. Conflict Resolution: What If Local and Server Data Differ?

There is one more problem we need to consider.

Suppose a user edits a task offline. Meanwhile, another user edits that same task on a different device and successfully saves the change to the backend.

When the first user reconnects, both versions exist:

  • The locally modified version.
  • The newer server version.

Which one should win?

This is a data conflict.

There is no universally correct conflict-resolution strategy. The right approach depends on the application and the importance of the data.

Some common strategies include:

Last-write-wins: The most recent update takes precedence. This is relatively simple, but it can silently overwrite meaningful changes.

Version-based conflict detection: Each record has a version number. The server rejects an update if the client is editing an outdated version, allowing the application to resolve the conflict.

Manual conflict resolution: The user is shown the conflicting versions and decides which changes to keep.

For a simple task board, last-write-wins might be acceptable in some situations. For financial transactions, collaborative documents, or other sensitive data, blindly overwriting changes would be a dangerous design choice.

Conflict resolution should be a deliberate product and engineering decision.

9. Putting the Architecture Together

Let's bring these concepts together.

Our resilient Task Board now has several distinct responsibilities:

Component Responsibility
Service Worker Intercepts requests and supports offline application loading
Cache API Stores application resources and selected network responses
IndexedDB Stores local application data and pending operations
React application Renders data and handles user interactions
Backend API Processes application operations and coordinates shared data
MySQL Stores authoritative application records

The overall data flow becomes:

  1. The Service Worker helps the application load.
  2. The React application retrieves locally available data from IndexedDB.
  3. The user interacts with the application.
  4. Changes are saved locally and recorded for synchronization.
  5. When the backend is reachable, pending operations are sent.
  6. The backend validates and processes operations, using idempotency protection where appropriate.
  7. Confirmed changes are reflected in the local database.

This is the foundation of a resilient, offline-capable application.

It is not enough to cache a page and call the application offline-ready. We must also think about the data, user actions, synchronization, and recovery.

10. Final Thoughts: Resilience Is an Architectural Decision

Building for unreliable networks requires us to change how we think about web applications.

Instead of assuming that every user action can immediately reach the backend, we design for the possibility that communication will be delayed or interrupted.

Instead of treating network failure as an exceptional situation, we make it part of the application's expected operating conditions.

And instead of leaving users uncertain about whether their actions were successful, we design clear states for pending, synchronized, and failed operations.

The key lessons from this series are:

  • Use the Service Worker and Cache API to support application availability.
  • Use IndexedDB for structured local application data.
  • Consider local-first reads to reduce dependency on network response times.
  • Use optimistic UI carefully to improve perceived responsiveness.
  • Queue offline mutations instead of losing user operations.
  • Implement idempotency to make retries safer.
  • Use sensible retry strategies and account for conflicts.

A resilient application is not one that never experiences network failure.

It is one that remains useful, communicates honestly with its users, and recovers gracefully when the network eventually returns.

The network may be unreliable. Your application doesn't have to be.

Explore the Project

Follow along with the Resilient Task Board repository, starting from the original version before the resilience improvements discussed in this series.

Further Reading