Skip to main content
To have a coding agent migrate your app, copy the prompt for your coding agent. It points the agent at this guide and the companion repo.
Field and delivery apps must continue to operate even when the device is offline. This guide takes an online-only app built with .NET MAUI, ASP.NET Core, and SQL Server, and makes it work offline by using a local-first architecture. The SQL Server database and the backend API are largely unchanged. The app gets a local SQLite database, and it reads from and writes to only that database. There is one code path, whether the device is online or offline. PowerSync syncs the local database with SQL Server. The example is a delivery-driver app (also referred to as a Courier app in non-US markets). Drivers see today’s stops and record each one as delivered or failed. Dispatch is a back-office system that writes straight to SQL Server, and it adds and cancels stops. The companion repo has both versions: the original REST app on the main branch, and the updated architecture using PowerSync on the powersync-existing-api branch.

The Starting Point: An Online-Only REST App

The app calls the backend API for everything. A dispatch script writes to SQL Server directly, as a back-office or ERP system would. There are two tables, both with server-generated NEWSEQUENTIALID() GUIDs:
  • stops: driver, route date, sequence, recipient, address, and a status of assigned, delivered, failed, or canceled.
  • deliveries: one row per attempt, with the outcome, a note, and recorded_at.
The backend API signs RS256 tokens and publishes the public key at /.well-known/jwks.json, the way Entra ID or any other identity provider does. To record an outcome, the app calls POST /api/stops/{id}/deliveries. This endpoint enforces the app’s one business rule: it returns 409 if dispatch canceled the stop or the stop is already delivered. The endpoint locks the stop row first, so a cancel that arrives at the same moment can’t slip in. The full code is on the repo’s main branch.
Route list with eight stops, two delivered, one failed, and one canceled

The day's route, part done.

Stop page showing one failed attempt and the Delivered and Failed buttons

A stop with a failed attempt, ready to try again.

Failure Modes

The REST-based app fails in three ways:
  • If the driver records an outcome while offline, they get an error banner and have to try again later.
  • If the driver opens the app while offline, the screen is empty, so they can’t see where to go.
  • If dispatch cancels a stop, it still shows as assigned until the driver refreshes. A delivery attempt on it then fails with a 409.
In the example scenario below, dispatch canceled stop 4 after the driver opened it. The page still shows the stop as assigned. When the driver taps Delivered, the backend API returns 409. In the same way, the route list keeps showing a canceled stop as assigned until the driver pulls to refresh.
Stop 4 page showing status assigned

Stop 4, canceled by dispatch, still shows as assigned.

Stop 4 page with the error banner Dispatch canceled this stop

Tapping Delivered gets a 409.

Empty route list with the error banner Couldn't reach the server

No network: opening the app shows an empty route.

Baseline Code

The route list loads when the page appears and on pull-to-refresh. With no network, the list is empty:
Recording an outcome makes the HTTP call. It has three failure paths (a 409, a network error, and a failed reload), a reload, and a fallback for when the reload fails:

Migrating to Local-First

In the new architecture, the app reads and writes its local SQLite database. The PowerSync Service streams changes from SQL Server to the device, and the client SDK uploads local writes through the existing backend API. To see a full diff of the migration, including the backend API change, see the pull request in the companion repo.

What Changes and What Stays

Prompt for Your Coding Agent

To have a coding agent do this migration, copy this prompt. The agent reads this guide and the companion repo, maps them onto your app, and asks you about anything it can’t find before it writes code.
Build with AI

Step 1: Prepare SQL Server for CDC

The PowerSync Service reads changes from SQL Server through Change Data Capture (CDC). Your tables are unchanged: CDC adds change tables next to them. A SQL Server Agent job fills those tables from the transaction log. The PowerSync Service polls the change tables and turns each change into sync data. This step usually needs a DBA. Check the requirements below, then run the setup script.

SQL Server Compatibility Checklist

  • Edition: Use SQL Server 2019 or later (Standard, Enterprise, Developer, or Evaluation), Azure SQL Database, or Azure SQL Managed Instance. Azure SQL Database needs a vCore tier, or S3 and up on DTU. Express and Web editions don’t have CDC, so the PowerSync Service can’t replicate from them.
  • Permissions: Enabling CDC on the database needs sysadmin (db_owner on Azure SQL). You do this once. The PowerSync Service then connects as a read-only user.
  • SQL Server Agent must be running: If the Agent is stopped, enabling CDC still succeeds, but the change tables stay empty and the PowerSync Service never sees an update. In the official Docker image, the Agent is off by default, so set MSSQL_AGENT_ENABLED=true. This item doesn’t apply to Azure SQL Database, which manages the CDC jobs itself.
  • Transaction log: CDC reads the log, so SQL Server can’t free log space until the capture job has processed it. Monitor log growth and the retention of the CDC cleanup job.
  • Delayed durability must be off: SQL Server refuses to enable CDC on a database with delayed durability set. It also refuses to turn delayed durability on (FORCED or ALLOWED) while CDC is enabled. Run SELECT delayed_durability_desc FROM sys.databases and make sure that it returns DISABLED.
  • Sync tables, not views: CDC captures only tables. If you name a view in your Sync Streams, the PowerSync Service stops replicating and logs the PowerSync error PSYNC_S1602. The solution is to sync the underlying tables and do the join on the client.
  • Don’t sync computed columns: The initial copy reads the real value, but CDC records computed columns (persisted or not) as NULL, so every later insert or update syncs NULL. Leave them out of your Sync Stream queries and compute the value on the client, or write it to a normal column.
  • Prefer a single-column primary key: The PowerSync Service copies tables keyed on one column in resumable batches. It copies other tables (composite keys or no key) in one pass, and starts again from zero if it restarts mid-copy.

The Setup Script

The companion repo does all of this in one idempotent script, db/powersync.sql, which runs as a one-shot container after the app’s own init.sql. The steps below show a trimmed version. Replace DeliveryApp and the table names with your own.
1

Fail Early If SQL Server Agent Is Off

If the Agent is stopped, CDC enables without error but captures nothing. This check stops the script instead.
2

Enable CDC on the Database, Then on Each Table to Sync

Name every replicated table here and in your Sync Streams (Step 3).
3

Create a Read-Only Login for the PowerSync Service

The script is a sqlcmd script: pass the password with -v POWERSYNC_DB_PASSWORD="...". The ALTER LOGIN branch makes sure that running the script again picks up a changed password.
4

Add the Checkpoints Table

The PowerSync Service writes to this table to mark consistent points in the CDC stream. The table needs CDC too.
5

Make the Capture Job Scan Every Second

The default interval is 5 seconds. This interval is most of the delay between a write in SQL Server and the change reaching devices.
The new settings take effect only when the capture job restarts. Restart SQL Server Agent, stop and start the job, or restart the SQL Server container.On Azure SQL Database, you can’t change this setting. The capture interval is fixed at 20 seconds, which sets a floor on how quickly changes in SQL Server reach devices.

Step 2: Run the PowerSync Service

This guide self-hosts the PowerSync Service with Docker Compose (see the repo’s docker-compose.yml). You can also use PowerSync Cloud.
PowerSync Cloud Private Endpoints don’t currently support SQL Server, so an on-premises database needs a network route that PowerSync Cloud can reach.

Configure the PowerSync Service

service.yaml
PS_DATA_SOURCE_URI has the form mssql://powersync_user:<password>@sqlserver:1433/DeliveryApp.
If your password isn’t URL-safe, you must URL-encode it.
Devices authenticate to the PowerSync Service with a JWT. If your backend API already issues JWTs signed with an asymmetric key and publishes a JWKS (as Entra ID, Auth0, and most identity providers do), point client_auth.jwks_uri at it and set the audience that your tokens carry. See Custom Authentication for other token setups.

Step 3: Define the Data That Each Device Gets

Use Sync Streams to define which rows go to which device. In this example, each driver gets their own stops and delivery attempts:
sync-config.yaml
  • auth.user_id() is the sub claim from the token in Step 2. The filter runs in the PowerSync Service, so a device receives only its own driver’s rows.
  • auto_subscribe: true means that the app doesn’t have to subscribe to this stream. It syncs as soon as the app connects.
After you change this file, restart the PowerSync Service container. A change to Sync Streams makes the PowerSync Service reprocess the data. That takes seconds for this example, but on a large database you need to plan for it (see Schema Changes).

Step 4: Swap the App’s Reads to Local SQLite

Add version 1.0.1 of the PowerSync.Common NuGet package. It includes the native libraries for iOS and Android, so you don’t need the PowerSync.Maui package.

Define the Schema

The client-side schema is one C# class for every local table. The [Column] attributes declare the local columns. Each class also implements IFromRow<T>, so it can serve as a query result type, and the classes replace the backend API’s DTOs:
AppSchema.cs

On Startup: Open the Database and Connect

Open the database and call Connect() during app init. The pages read local data, so they don’t wait for the connection:
Database.cs
App.xaml.cs
The connector’s FetchCredentials() gets a token from the backend API’s existing token endpoint. The PowerSync Service checks the token against the same JWKS as the backend API:
DeliveryConnector.cs

Replace the REST-Based Loads with Watch Queries

The route list now watches a local query instead of calling the backend API. A stop that dispatch adds or cancels appears without a refresh, and the list works offline:

Code You No Longer Need

  • The GET calls in the backend API client.
  • The backend API’s DTOs. The schema classes replace them.
  • The load and reload methods, and their error paths.
  • Both pull-to-refresh views.
Route list after the migration, read from local SQLite

The route list, read from the local database.

Stop page after the migration, showing two earlier attempts

The stop page, read from the local database.

Step 5: Move Writes to the Upload Queue

Record an Outcome Locally

Recording an outcome becomes one local transaction: insert the delivery, then update the stop’s status. There is no network call, so there is no network error path. The page updates through its watched queries:
The device generates the delivery’s ID with Guid.NewGuid(), in upper case. Because the ID exists before the upload, a retry or an offline create targets the same row. See Client ID.

Upload Through the Existing API

The PowerSync client SDK automatically places writes into its upload queue, and calls the connector’s UploadData(), which posts the delivery to the existing API endpoint.
DeliveryConnector.cs
UploadData() handles each response as the existing API guide describes:
  • 2xx: applied.
  • 400, 404, and 409: dropped and shown to the driver.
  • 401: refresh the token and retry.
  • Everything else: retried.

Change One Endpoint in the Backend API

The delivery endpoint now accepts the device’s ID and the time of the tap. A retry can repeat a delivery that the backend API already recorded, so the endpoint returns 200 for a repeat before it applies the business rule. Otherwise, a retried “delivered” would get a 409 because the stop is already delivered:

The Business Rule Stays in the Backend API

The business rule is unchanged. If a driver records a delivery offline on a stop that dispatch then cancels, the upload gets a 409, and a banner tells the driver. At the next sync, the local delivery disappears and the stop shows as canceled. This needs no extra code.
Baseline stop page with the error banner Dispatch canceled this stop

Before: rejected while online.

Stop page with a banner saying the delivered outcome for stop 5 wasn't saved because dispatch canceled the stop

After: recorded offline, then rejected on upload.

Before you ship: The companion repo is the minimum code needed for demonstration. It marks production hardening with // Production: comments:
  • An ID reused by another driver: The insert fails with a 500, which the client retries forever. Check for this case and return 400.
  • The device clock: recorded_at comes from the device. Check it against the backend API’s clock.
  • Rejections across restarts: The rejection message is lost if the app restarts before the driver sees it. Keep it in a local-only table, or have the backend API record rejections in a table that syncs back.

Step 6: Dispatch Changes Show Without a Refresh

Dispatch still writes straight to SQL Server. CDC picks up the change, and the PowerSync Service streams it to the device. Nothing in the app polls or refreshes. The driver gets these updates without any app code:
  • A stop that dispatch cancels or adds shows up while the driver is looking at the list.
  • An attempt recorded on another device appears in seconds.
  • Writes from any system reach the device, not only writes through your backend API.
Route list with stop 6 assigned

Stop 6 is assigned.

Route list with stop 6 shown as canceled

Seconds after dispatch cancels it, with no refresh.

Step 7: Test Offline Behavior

To test offline behavior, cut the simulator’s network, for example with the 100% Loss profile in Network Link Conditioner.
Baseline stop page with the error banner Couldn't reach the server

Before: recording an outcome with no network shows an error.

Stop page showing the delivered status and the line Offline. Changes pending.

After: the delivery is saved and queued for upload.

Baseline empty route list with an error banner

Before: opening the app with no network shows an empty route.

Full route list shown while offline, with the line Offline. Changes pending.

After: the full route comes from the local database.

The PowerSync client SDK calls FetchCredentials() on every connect, and in this example that calls your backend API’s token endpoint. If your backend API is down, the app can’t connect to the PowerSync Service either. Reads still work, because they’re local. To keep sync running through an API outage, cache the token on the device and return it from FetchCredentials() until it expires.

Schema Changes

SQL Server schema changes need a few manual steps. For example, to add a signed_by column to deliveries in the companion repo:
  1. Run ALTER TABLE. Replication continues without the new column, and the PowerSync Service logs Schema drift detected … Deploy a new sync config.
  2. Create a new capture instance with a new name. A table can have at most 2 capture instances.
  3. Redeploy the Sync Config. A restart alone does nothing, but a comment-only change counts as a redeploy. The redeploy starts a new replication stream with a full new snapshot. Clients keep syncing from the old stream until the new one is ready.
  4. Disable the old capture instance.
  5. On the client, add a property to the schema class. The client schema has no migrations.
See SQL Server Specifics for the full workflow.

How This Compares with Datasync and Dotmim.Sync

CommunityToolkit Datasync and Dotmim.Sync are the other common options for MAUI and SQL Server.

Next Steps

Companion Repo

The main branch is the REST app, and powersync-existing-api adds PowerSync.

SQL Server Setup

Full SQL Server source database setup.

.NET SDK

Reference for the .NET SDK.

Use Your Existing API

How to upload local writes through the API you already have.

Offline-First Architecture Jargon

The terms and patterns behind this guide.