---
title: "How do you queue and synchronize writes while offline and push them once online?"  
description: "How do you queue and synchronize writes while offline and push them once online?"  
author: "Rana Sunny"  
published: 2025-07-07  
updated: 2025-07-07  
canonical: https://www.mindstick.com/interview/34324/how-do-you-queue-and-synchronize-writes-while-offline-and-push-them-once-online  
category: "IndexedDB"  
tags: ["indexeddb"]  
reading_time: 4 minutes  

---

# How do you queue and synchronize writes while offline and push them once online?

To queue and synchronize writes while offline and push them once online (commonly used in offline-first web/mobile apps), you typically follow this pattern:

## General Strategy

- **Queue Writes Locally (Offline)**

   - Store write actions (create/update/delete) in an offline queue, such as:

      - **IndexedDB** (Web)
      - **localStorage** (not recommended for complex writes)
      - **SQLite** (Mobile)
      - **Dexie.js** or **localForage** (for easier IndexedDB handling)

- **Detect Online Status**

   - Use `window.navigator.onLine` and listen for:

```javascript
window.addEventListener("online", syncQueuedWrites);
```

- **Synchronize (Push) Writes When Online**

   - On `online` event or app load (if online), process queued writes:

      - Read each queued item.
      - Send the write to the server.
      - If successful, remove the item from the queue.
      - Optionally handle retry logic and conflict resolution.

## Sample (Dexie.js Example)

### 1. Define Your IndexedDB Store (Queue)

```javascript
const db = new Dexie("OfflineWriteDB");
db.version(1).stores({
    items: '++id, type, payload',
});
```

### 2. Queue Write Action Offline

```javascript
async function queueWrite(type, payload) {
    await db.items.add({ type, payload });
}
```

### 3. Sync When Online

```javascript
async function syncQueuedWrites() {
    const allItems = await db.items.toArray();

    for (const item of allItems) {
        try {
            const response = await fetch('/api/sync', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(item)
            });

            if (response.ok) {
                await db.items.delete(item.id); // remove if sync successful
            }
        } catch (err) {
            console.error("Sync failed for item", item.id, err);
            // Optionally retry or mark failed
        }
    }
}
```

### 4. Detect Online and Start Sync

```javascript
window.addEventListener("online", syncQueuedWrites);
```

## Considerations

| Feature | Notes |
| --- | --- |
| **Conflict Resolution** | Server should return proper status/errors if conflicts occur (e.g. versioning, timestamps) |
| **Deduplication** | Ensure you don't double-send operations (e.g., mark with IDs) |
| **Background Sync (PWAs)** | Use Background Sync API for advanced use |
| **Retries** | Exponential backoff or retry count in queue schema |
| **Encryption** | Encrypt local storage if handling sensitive data |

## Tools/Libraries

- **Dexie.js** – Simplified IndexedDB
- **localForage** – Abstracts IndexedDB, WebSQL, localStorage
- **Workbox** – Service Worker tooling for caching + background sync
- **RxDB**, **PouchDB** – Full sync-capable offline-first databases

## Answers

### Answer by Rana Sunny

To queue and synchronize writes while offline and push them once online (commonly used in offline-first web/mobile apps), you typically follow this pattern:

## General Strategy

- **Queue Writes Locally (Offline)**

   - Store write actions (create/update/delete) in an offline queue, such as:

      - **IndexedDB** (Web)
      - **localStorage** (not recommended for complex writes)
      - **SQLite** (Mobile)
      - **Dexie.js** or **localForage** (for easier IndexedDB handling)

- **Detect Online Status**

   - Use `window.navigator.onLine` and listen for:

```javascript
window.addEventListener("online", syncQueuedWrites);
```

- **Synchronize (Push) Writes When Online**

   - On `online` event or app load (if online), process queued writes:

      - Read each queued item.
      - Send the write to the server.
      - If successful, remove the item from the queue.
      - Optionally handle retry logic and conflict resolution.

## Sample (Dexie.js Example)

### 1. Define Your IndexedDB Store (Queue)

```javascript
const db = new Dexie("OfflineWriteDB");
db.version(1).stores({
    items: '++id, type, payload',
});
```

### 2. Queue Write Action Offline

```javascript
async function queueWrite(type, payload) {
    await db.items.add({ type, payload });
}
```

### 3. Sync When Online

```javascript
async function syncQueuedWrites() {
    const allItems = await db.items.toArray();

    for (const item of allItems) {
        try {
            const response = await fetch('/api/sync', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(item)
            });

            if (response.ok) {
                await db.items.delete(item.id); // remove if sync successful
            }
        } catch (err) {
            console.error("Sync failed for item", item.id, err);
            // Optionally retry or mark failed
        }
    }
}
```

### 4. Detect Online and Start Sync

```javascript
window.addEventListener("online", syncQueuedWrites);
```

## Considerations

| Feature | Notes |
| --- | --- |
| **Conflict Resolution** | Server should return proper status/errors if conflicts occur (e.g. versioning, timestamps) |
| **Deduplication** | Ensure you don't double-send operations (e.g., mark with IDs) |
| **Background Sync (PWAs)** | Use Background Sync API for advanced use |
| **Retries** | Exponential backoff or retry count in queue schema |
| **Encryption** | Encrypt local storage if handling sensitive data |

## Tools/Libraries

- **Dexie.js** – Simplified IndexedDB
- **localForage** – Abstracts IndexedDB, WebSQL, localStorage
- **Workbox** – Service Worker tooling for caching + background sync
- **RxDB**, **PouchDB** – Full sync-capable offline-first databases


---

Original Source: https://www.mindstick.com/interview/34324/how-do-you-queue-and-synchronize-writes-while-offline-and-push-them-once-online

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
