> ## Documentation Index
> Fetch the complete documentation index at: https://docs.powersync.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Building an Offline-First Architecture for Proof of Delivery (POD)

> Keep a delivery driver app scanning packages and capturing proof of delivery even in dead zones.

Delivery drivers (often called couriers outside the US) frequently work where there is no signal or unreliable connectivity: underground parking garages, basements, loading docks, and rural routes. A driver app must keep scanning packages and capturing proof of delivery (POD) in those places.

A scan is business-critical data. A lost scan can mean a lost package or a disputed delivery, so it must be treated as fact from the moment the driver records it.

Many driver apps have an "offline mode". These have some common failure cases:

* The app posts each scan to the API and queues it only when the call fails. Now there are two code paths, and the offline path is harder to test.
* A background job retries a scan after a timeout, and the server records the scan event twice.
* A large POD photo stuck on a weak uplink blocks the scan events queued behind it.
* Dispatch cancels a stop while the driver is in a dead zone, and the driver's delivery collides with the cancellation.

A few architecture patterns avoid all of these. This guide explains those patterns and shows how to implement them using PowerSync.

> [!NOTE]
>
> Although PowerSync works with many [front-end stacks](https://docs.powersync.com/client-sdks/overview.md) and [backend databases](https://docs.powersync.com/configuration/source-db/setup.md), the example code below uses React Native and Postgres. In our *Migration Guides* section, we also have a complete delivery driver example app that uses SQL Server and .NET MAUI. See [Migrating a SQL Server and .NET MAUI App to Offline-First](https://docs.powersync.com/migration-guides/sql-server-maui.md).

## 1. Put a Database on the Driver's Device

For robust offline behavior, the network must not be on the critical path for a driver accessing their route or scanning packages.

PowerSync gives the app on the driver's device (a phone, tablet, or rugged handheld) a [client-side SQLite database](https://docs.powersync.com/resources/architecture-guides/offline-first-architecture.md#local-first-database). Whether online or offline, the app reads and writes only to that database. The PowerSync client SDK downloads changes via the PowerSync Service based on your [Sync Streams](https://docs.powersync.com/sync/streams/overview.md), and uploads writes via your backend API. The SDK automatically handles retries of failed uploads.

When wiring up the PowerSync client SDK, you define a schema for the local SQLite database that matches your Sync Streams. Here is what a basic schema for a delivery driver app typically looks like: A route is the driver's `stops` rows for the day, flowing down from dispatch. Proof of delivery is one `deliveries` row per attempt, with an outcome, plus `photo_id` and `signature_id` pointing to attachments.

```ts powersync/AppSchema.ts theme={null}
import { AttachmentTable, column, Schema, Table } from '@powersync/react-native';

// Flows down from dispatch
const stops = new Table({
  sequence: column.integer,
  recipient: column.text,
  address: column.text,
  status: column.text // 'assigned' | 'delivered' | 'failed' | 'cancelled'
});

// Flows up from the driver
const deliveries = new Table({
  stop_id: column.text,
  driver_id: column.text,
  outcome: column.text, // 'delivered' | 'failed'
  photo_id: column.text,
  signature_id: column.text
});

const scan_events = new Table({
  stop_id: column.text, // null for warehouse scans
  driver_id: column.text,
  package_barcode: column.text,
  kind: column.text, // 'loaded' | 'out_for_delivery' | 'delivered' | 'failed'
  failure_reason: column.text, // 'no_one_home' | 'refused' | 'no_access'
  lat: column.real,
  lng: column.real,
  scanned_at: column.text, // device clock
  received_at: column.text // set by your backend
});

export const AppSchema = new Schema({
  stops, deliveries, scan_events, attachments: new AttachmentTable()
});
```

See the [React Native & Expo SDK reference](https://docs.powersync.com/client-sdks/reference/react-native-and-expo.md) for a detailed setup guide.

## 2. Record Every Scan as an Append-Only Scan Event

Edits to scan rows break audit trails and can lead to data inconsistencies. A retried upload must not overwrite the original scan event.

To address this, every scan (loaded at the warehouse, out for delivery, delivered, failed) is a new `scan_events` row. Nothing is updated or deleted, so a package's history is the list of its scan events, and a retried upload can't change a scan already recorded.

With PowerSync, `scan_events` is a standard synced table. Your app writes each scan to it directly. The PowerSync client SDK manages uploading those writes via your backend API. You configure a [Sync Stream](https://docs.powersync.com/sync/streams/overview.md) that sends each driver's own scan events back to the device ([section 7](#7-load-the-route-at-the-warehouse-and-sync-only-the-driver’s-stops)), so the full history stays available after upload.

A failed delivery attempt is a `deliveries` row with outcome `failed`, plus a scan event with `kind = 'failed'` and a `failure_reason`. A later attempt is a new row.

Record `lat` and `lng` on each scan event, since location is part of the evidence. Keep two clocks: `scanned_at` is what the device said, and `received_at` is set by your backend on insert (`null` on the device until the row syncs back). The device's clock can be wrong, so your backend never overwrites `scanned_at`.

Write the scan event and the delivery in one `writeTransaction()`, so they upload together:

```ts deliveries/recordDelivery.ts theme={null}
import { powersync } from '../powersync/system';

type Scan = { stopId: string; driverId: string; barcode: string; lat: number; lng: number };

export async function recordDelivery(s: Scan, outcome: 'delivered' | 'failed', failureReason: string | null) {
  return powersync.writeTransaction(async (tx) => {
    const { id: deliveryId } = await tx.get<{ id: string }>('SELECT uuid() AS id');
    await tx.execute(
      'INSERT INTO deliveries (id, stop_id, driver_id, outcome) VALUES (?, ?, ?, ?)',
      [deliveryId, s.stopId, s.driverId, outcome]
    );
    await tx.execute(
      `INSERT INTO scan_events (id, stop_id, driver_id, package_barcode, kind, failure_reason, lat, lng, scanned_at)
       VALUES (uuid(), ?, ?, ?, ?, ?, ?, ?, ?)`,
      [s.stopId, s.driverId, s.barcode, outcome, failureReason, s.lat, s.lng, new Date().toISOString()]
    );
    return deliveryId;
  });
}
```

## 3. Make Every Upload Idempotent by Generating IDs on the Device

Due to the flaky nature of networks, when retrying write uploads, the server can sometimes apply the write, but the client does not receive a response. Therefore, write operations should be made idempotent, which requires the use of an [Idempotency Key](https://docs.powersync.com/resources/architecture-guides/offline-first-architecture.md#idempotency-key),

PowerSync provides the `uuid()` SQLite function (see [Client ID](https://docs.powersync.com/sync/advanced/client-id.md)), so you can generate a unique ID for each row on the device, without relying on the network. In the above example, we use `uuid()` for the `deliveries` and `scan_events` rows. Your backend stores those IDs as the primary keys for the rows.

In your backend implementation for handling writes, inserts should be processed using `ON CONFLICT (id) DO NOTHING` to make them idempotent. If a scan is uploaded multiple times, the repeats have no effect.

```sql theme={null}
-- received_at defaults to now(); a trigger sets is_current_route while the driver's route is open.
INSERT INTO scan_events (id, stop_id, driver_id, package_barcode, kind, failure_reason, lat, lng, scanned_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (id) DO NOTHING;
```

Your write endpoint must [commit to the source database before it responds](https://docs.powersync.com/handling-writes/write-path/concepts.md#applying-writes-before-responding). Otherwise, the client completes a scan that your backend could still lose or reject.

## 4. Scan Anytime and Upload When Online

Scans recorded while the device is offline must reach your backend in order, even across app restarts. DIY sync implementations need an [outbox](https://docs.powersync.com/resources/architecture-guides/offline-first-architecture.md#outbox-pattern) table plus a worker that drains and retries it, and only one instance of that worker may ever run on the device.

When PowerSync, you don't need to build an outbox. PowerSync records every write to a synced table in its [upload queue](https://docs.powersync.com/architecture/client-architecture.md#writing-data-via-sqlite-database-and-upload-queue). You define an `uploadData()` function that determines how entries in that upload queue are uploaded to your backend. The PowerSync SDK calls that `uploadData()` function after local writes, on reconnection, and automatically retries after failures – so queued scans upload as soon as the network allows. Entries leave the queue only once they have been successfully processed.

```ts powersync/Connector.ts theme={null}
// Inside your backend connector
async uploadData(database: CommonPowerSyncDatabase) {
  const transaction = await database.getNextCrudTransaction();
  if (!transaction) return;

  const res = await fetch(`${API_URL}/driver/upload`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${await getDriverToken()}` },
    body: JSON.stringify({
      ops: transaction.crud.map((op) => ({ op: op.op, table: op.table, id: op.id, data: op.opData }))
    })
  });

  if (res.status >= 400 && res.status < 500 && res.status !== 401) {
    // Production: keep the rejection in a local-only table so it survives an app restart before the driver sees it.
    showRejection(await res.text());
  } else if (res.status === 401) {
    clearDriverToken(); // The retry fetches a new token.
    throw new Error('Token expired');
  } else if (!res.ok) {
    throw new Error(`Upload failed: ${res.status}`); // No network, a timeout, a 5xx: retried.
  }

  await transaction.complete();
}
```

Your backend should return a 200 for an ID it already inserted, so a retried insert doesn't yield an error. Reject any `UPDATE` or `DELETE` on `scan_events`, since they are considered append-only.

## 5. Upload POD Photos and Signatures as Attachments

Keep photos and signatures out of your database rows. Embedding image data as base64 or binary blobs bloats the local database, slows queries and sync, and puts multi-megabyte uploads in the same queue as the scan events and status changes. Store each file in object storage and keep only its ID in the row.

PowerSync's built-in Attachment Helpers can handle POD photos and signatures. The `deliveries` row holds the attachment IDs.

For more details on how this works, refer to [Attachments / Files](https://docs.powersync.com/client-sdks/advanced/attachments.md).

```ts pod/attachPhoto.ts theme={null}
import { podQueue } from './podQueue';

export async function attachPhoto(deliveryId: string, cameraUri: string) {
  // Production: resize/compress the photo before saving it.
  // Production: use resumable/multipart uploads in a transport adapter for large files.
  await podQueue.saveFileFromUri({
    localUri: cameraUri,
    fileExtension: 'jpg',
    mediaType: 'image/jpeg',
    updateHook: async (tx, attachment) => {
      await tx.execute('UPDATE deliveries SET photo_id = ? WHERE id = ?', [attachment.id, deliveryId]);
    }
  });
}
```

Give the `AttachmentQueue` an `errorHandler` whose `onUploadError` returns `true`, so failed uploads retry. Returning `false` archives the file, which loses the POD evidence.

Attachments upload on their own queue, not with the row, so your backend must accept a `photo_id` before the file arrives. The upload to storage must also be safe to repeat, since a killed app can re-upload a photo that already finished.

## 6. Write Down Your Conflict Rules

When a device comes back online, its local state and pending uploads may conflict with what was written to the backend while it was offline. Your backend needs [conflict resolution rules](https://docs.powersync.com/handling-writes/handling-update-conflicts.md) to handle this.

Append-only rows with client IDs can't conflict, so this design has minimal conflict rules:

* **Scan events:** never conflict and are never rejected. Your backend records them even against a cancelled stop.
* **Stops:** dispatch-owned. Only dispatch creates and cancels them; drivers only record outcomes. Your backend sets `stops.status` from the delivery it receives. Until then, your app can show a stop as done if it has a local `deliveries` row.
* **A delivery on a stop which dispatch already cancelled:** your backend decides. For example, you can record the attempted delivery in a dead-letter queue and propagate an error message back to the driver via a synced table.

While uploads are queued, PowerSync doesn't apply downloads (see [Consistency](https://docs.powersync.com/architecture/consistency.md)), so a cancelled stop shows on the device only after the driver's scans upload.

Dispatchers read scans and POD from your backend database as soon as they upload.

## 7. Load the Route at the Warehouse and Sync Only the Driver's Stops

The app must have the driver's scheduled stops available even while offline. Each device should download only the stops and deliveries for its own driver.

PowerSync provides [Sync Streams](https://docs.powersync.com/sync/streams/overview.md) as a declarative way to define what each device receives and stores locally. The driver is `auth.user_id()` from the JWT, and the `my_route` stream below filters on it (see [Using Parameters](https://docs.powersync.com/sync/streams/parameters.md)).

The `my_route` stream sends the driver's stops and deliveries, plus their own `scan_events`. Without the `scan_events` query, scans disappear from the device after upload.

For the purposes of the example below, the `is_current_route` flag is set by the backend to indicate the current active route for the driver.

```yaml theme={null}
config:
  edition: 3

streams:
  my_route:
    auto_subscribe: true
    queries:
      - SELECT * FROM stops WHERE driver_id = auth.user_id() AND is_current_route = true
      - SELECT * FROM deliveries WHERE driver_id = auth.user_id() AND is_current_route = true
      - SELECT * FROM scan_events WHERE driver_id = auth.user_id() AND is_current_route = true
```

`my_route` downloads the scheduled stops before the driver is dispatched, while their device is connected. Before leaving the warehouse or going offline, the driver should be able to check whether their device is synced. This can be implemented in your UI using `SyncStatus` provided by the PowerSync client SDK.

## 8. Show the Driver What's Still Waiting to Upload

It can be helpful to show the driver which scans and POD are safe on the device but not yet uploaded.

PowerSync's `SyncStatus` gives `connected`, `uploading`, and `lastSyncedAt` (see [Production Readiness Guide](https://docs.powersync.com/maintenance-ops/production-readiness-guide.md#sdk-diagnostics)). The number of pending uploads (i.e. scans and deliveries) in the upload queue can also be displayed to the driver: `SELECT COUNT(*) FROM ps_crud`. Pending photos and signatures can also be shown: they are rows in the local `attachments` table with state `QUEUED_UPLOAD`.

## What PowerSync Removes from a DIY Design

| DIY component | PowerSync equivalent |
| - | - |
| Hand-written outbox table and "mark as sent" logic | Upload queue, filled automatically on every write to a synced table |
| Background worker with retries, limited to a single instance | SDK calls `uploadData()` after writes, on reconnect and after failures |
| Photo upload queue with its own retry state | `AttachmentQueue` with a streaming transport. |
| Logic to merge dispatch changes with unsent scans | Not needed: the client doesn't apply downloads while uploads are pending |
| Per-driver "changes since" API and sync cursor | The `my_route` Sync Stream. Each device downloads only what changed in its stream |

You still need to implement:

1. Your idempotent write endpoint, including rejection handling
2. Wiring up the [Attachment Helper](https://docs.powersync.com/client-sdks/advanced/attachments.md)
3. Driver auth and JWTs (your backend sets `driver_id` from the JWT)
4. Dispatch functionality that maintains the driver's scheduled stops

## Next Steps

> [card] [Setup Guide](https://docs.powersync.com/intro/setup-guide.md)
>
> Connect a source database and client app.

> [card] [Attachments / Files](https://docs.powersync.com/client-sdks/advanced/attachments.md)
>
> Set up the attachment queue.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.