Building an offline-first note-taking PWA with a Django sync API
I wanted a handwriting app in the style of Notability that runs on a phone, a tablet and a laptop, keeps working on a bad connection, and syncs to a server I control. The catch: that server had to be cheap shared hosting with Python and nothing else. Inkwell is the result, an offline-first note-taking PWA with a small Django sync API behind it, and this post walks through how it is put together.
The code is open source at github.com/himaldahal/inkwell under the MIT licence.
The problem: notes can't wait for the network
A note-taking app that shows a spinner when the Wi-Fi drops is useless in a lecture hall or on a bus. So the first rule was that every write goes to the device first. The server is a backup and a way to reach your other devices, never something the pen waits on.
The second rule came from where I wanted to run it. Shared hosting with cPanel gives you a Python app behind Passenger, a database and a folder for files. There are no WebSockets, no Redis, no Celery and no Node on the server. That rules out most "real-time sync" stacks before you start.
Architecture of an offline-first note-taking PWA
The frontend is plain ES modules built with Vite, with no UI framework. Its runtime dependencies are idb for IndexedDB, pdfjs-dist and pdf-lib for PDFs, and tesseract.js for optional OCR. The backend's requirements.txt has two lines: Django 4.2 and WhiteNoise.
Because production has no Node, the built frontend is committed into backend/inkwell/static_app/ and WhiteNoise serves it. The CI workflow rebuilds the frontend on every push to main and fails if the committed build is out of date, then runs the Django tests and packages a deploy zip. Deploying is "upload the zip, run migrate, restart the app".
Records, tombstones and an outbox that survives crashes
On the device there are three synced stores: notebooks, notes and assets (images, PDFs, audio). Every record carries an id, an updatedAt timestamp in milliseconds, a deleted tombstone flag and a dirty flag. Saving a record sets dirty, and that flag is the outbox: it lives in IndexedDB, so a reload or a crash does not lose pending changes.
On the server, each of those records is one row in a single Record table: owner, kind, record id, timestamp, tombstone and the data as JSON text. Storing JSON as text keeps the same schema portable between SQLite and MySQL.
Pulling uses a cursor rather than timestamps. A one-row counter table hands out a global, increasing sequence number, and every write takes the next one:
def next_seqs(n):
SeqCounter.objects.get_or_create(pk=1)
SeqCounter.objects.filter(pk=1).update(value=F("value") + n)
top = SeqCounter.objects.get(pk=1).value
return top - n + 1
A client asks for everything with a sequence above its cursor. Device clocks never decide what gets pulled, so a phone with the wrong time cannot hide a change. The pull response also carries an ETag: a SHA-256 hash of the user, the cursor, the highest visible sequence number and a short signature of what is shared with them. When nothing has changed, the server answers 304 with an empty body, which keeps polling cheap.
Last-write-wins, with a safety net
Conflict handling is last-write-wins per record, by updatedAt. On push, the server validates and cleans every record, then compares it with what it already has:
ua = min(ua, now + FUTURE_SKEW_MS) # a clock in the future can't win forever
...
if ex:
newer = ex.updated_at > ua or (ex.updated_at == ua and ex.deleted and not deleted)
if newer:
conflicts.append(_rec_json(ex, me))
continue
The clamp matters. Without it, a device whose clock is a year ahead would win every conflict until that date. FUTURE_SKEW_MS is five minutes. The client also measures its offset from the server's clock and corrects outgoing timestamps when the gap is more than two seconds.
Plain last-write-wins silently drops work, which is not acceptable for handwriting. So when the server sends back a newer version of a note that also has unsynced local edits, the client keeps its own version as a copy before applying the server's:
if (kind === 'notes' && getSetting('sync.conflict') !== 'newest' && local.dirty
&& !local.deleted && !r.deleted && comparable(local) !== comparable({ ...data, id: r.id })) {
await putRecord('notes', { ...stripLocal(local), id: newId(),
title: (local.title || 'Untitled') + ' (conflict)', createdAt: Date.now() });
}
Nothing is lost. You see two notes and merge them by hand, the way Dropbox's "conflicted copy" works. The comparable() check skips the copy when both sides ended up with identical content.
When sync runs
The sync loop pushes first, then pulls. It runs on start-up, about three seconds after you stop editing, when the device comes back online, when the tab becomes visible again, and on a timer. The default timer is 30 seconds while the app is visible, at least 60 seconds after two minutes of no changes, and at least two minutes in the background. While a shared note is open it drops to 2.5 seconds, which is how collaboration works without WebSockets. An optional long-poll endpoint can be switched on where the host allows long requests.
Failures back off exponentially from five seconds up to a cap of five minutes, with plus or minus 25% jitter so a fleet of devices doesn't retry in lockstep. Where the browser supports Background Sync, the service worker wakes an open tab to flush the outbox. The service worker itself doesn't sync, because the data lives in the page's IndexedDB.
Smoothing ink without lag
The editor is the largest part of the codebase. One small piece I like is the input filter. Raw pointer events are jittery, especially from fingers and mice, but heavy smoothing makes the line trail behind the pen. Inkwell uses a One Euro filter, which smooths more when the pen moves slowly and less when it moves fast. Each input type has its own profile, because a stylus reports cleaner points than a finger:
const PROFILE = { pen: { min: 3.4, beta: 0.05 }, touch: { min: 1.5, beta: 0.035 }, mouse: { min: 1.3, beta: 0.03 } };
...
const cutoff = P.min + P.beta * Math.hypot(dx, dy), a = alpha(cutoff, dt);
x += (px - x) * a; y += (py - y) * a;
The speed is multiplied by the zoom level, so the filter feels the same whether you are zoomed in on a diagram or writing at page width.
What's in the repository
The chart counts lines with wc -l, excluding the committed build and migrations. The ink editor alone is bigger than the whole Django API. The backend has 30 model classes, 76 routes in api/urls.py and 93 test functions. Much of that backend is not sync at all: sharing with roles, public links, an admin dashboard, rate limits, and abuse controls for public sign-up forms.
Security got real attention too. Every query is scoped to the signed-in user, sign-in supports TOTP two-factor, and shared HTML is sanitised on the server. There is also optional end-to-end encryption: the client derives an AES-GCM key from a passphrase with PBKDF2 (310,000 iterations) and uploads only ciphertext, which the server stores as an opaque envelope.
Trade-offs and what I'd do next
- Whole-record conflicts. Last-write-wins works per note, not per stroke. Two people drawing on the same note at once can still produce a conflicted copy. Stroke-level merging would need a CRDT or per-page records.
- Polling, not push. A 2.5-second poll is fine for "who is editing", but it isn't true real-time. That was the price of running on shared hosting.
- Tested lightly on real devices. The README says so plainly: most features were exercised in a headless browser, and PDF export, audio and touch gestures need time on real tablets.
- Gaps. No layers yet, the "infinite" page is a large page that grows, OCR is weak on cursive, and the study module's data stays on the device.
Next I want per-page records to make conflicts rarer, and a proper round of testing with an iPad and Apple Pencil.
Takeaway
Offline-first is mostly a decision about where the truth lives. Put it on the device, treat the server as one more replica, pull with a server-side cursor rather than trusting client clocks, and never throw away a losing edit. With that in place, plain HTTP and a two-package Django backend go a long way.
You can see my other projects in the work section. If you're building something offline-first, or need a Django backend that runs on modest hosting, get in touch.
Himal Dahal
CTO at Daleema Group. Backend developer in Kathmandu.