FastHand Studio · Product

FastNotifications

The normal way to notify a phone is a vendor service: an account, a project id, and a delivery path you cannot read or run yourself. FastNotifications replaces it with one Cloudflare Worker. A Durable Object holds each user's socket open, a D1 table holds anything sent while they are away, and the whole guarantee is code you can inspect.

The repository contains the Worker, the D1 schema, the admin-key middleware, the device registration check, the reconnection replay, and a Kotlin test app.

Workers · Durable Objects · D1 · TypeScript · MIT

  1. 1A message is queuedIt waits in order while the phone is dark and nobody is holding it.
  2. 2The socket opensThe phone wakes and connects; one request is all it takes.
  3. 3The queue drainsWaiting messages are delivered in the order they arrived.
Figure 1. A phone lying flat, screen dark, with its notifications held in order above it. Every guarantee below is about the messages that arrive while nobody is holding the device.

What it does

Four guarantees, with no push service in the middle

Every notification either reaches a device now or is kept until it can. Here is what the code promises, one card each.

01

Online devices are notified instantly

The notification is written straight to the socket the device already has open. No polling, no third-party relay, no waiting for the next sync.

Durable Objecta small stateful worker that Cloudflare pins to one user, so it can hold that user's socket open and remember it.

WebSocket per user

02

Offline devices get queued, not dropped

If no socket is open, the notification is saved with status pending instead of disappearing. A phone that is switched off for six hours loses nothing.

Cloudflare D1Cloudflare's own SQL database. The queue lives in the same account as the Worker, so there is no second service to run.

status: "pending"

03

On reconnect the queue replays itself

When the socket opens again the client asks for what it missed and receives every unacknowledged notification, in the order it was sent.

Reconciliationcomparing what the server stored against what the device has seen, and sending only the difference.

GET /v1/notifications/pending

04

After an ack the record is deleted

Once the device has shown the notification it confirms the id, and that row is removed from the database permanently. Storage does not grow just because you sent things.

ACKshort for acknowledgement: the client's receipt that says "the user saw this", which is what makes deleting the row safe.

POST /v1/notifications/:id/ack

Next: the same four guarantees as one path a notification travels.

See the flow

How it works

One path: register, push, deliver, delete

Follow a single notification from the moment a device signs up to the moment its record disappears. The route is the same whether the device is awake or has been offline for a day; only the middle branch changes.

FastNotifications delivery flowA device registers with an email and device id. A backend sends a push. The NotificationCoordinator Durable Object checks the device is registered, then either writes the frame to an open WebSocket or stores a pending row in D1. On reconnect the client fetches pending notifications, and its acknowledgement deletes the row.1 · Device registersPOST /v1/devices/registeremail + deviceId bound to a user2 · Backend pushesPOST /v1/pushAuthorization: Bearer YOUR_API_KEY3 · Durable ObjectNotificationCoordinator, one per useris the device registered?4a · Onlinesocket already openframe { type: push }shown immediately4b · Offlineno open socketD1 row storedstatus = pending5 · Reconnect replaysGET /v1/notifications/pendingqueued rows arrive in order6 · Client acknowledgesPOST /v1/notifications/:id/ackthe D1 row is deleted
Figure 2. The journey of one notification. Step 3 is where the two outcomes split: an open socket delivers now, a closed one stores the row until the device returns.

The same flow, in words

The written version of Figure 2, for reading on a small screen or with a screen reader.

  1. 1 · Register onceThe app posts its email and device id. From then on, only a device that registered can open that user's socket.
  2. 2 · Push from anywhereAny server holding the API key can send to a user. No SDK, no vendor quota, no project id to register with Google.
  3. 3 · The user's object decidesOne Durable Object per user holds their connections, so delivering to that user's devices is a local loop, not a network hunt.
  4. 4a · If the socket is openThe frame goes down the existing WebSocket and the device shows it immediately.
  5. 4b · If it is notThe notification is written to D1 as pending and simply waits. Nothing is lost while the device is off.
  6. 5 · Reconnect replays the queueWhen the socket opens again the client requests /v1/notifications/pending and receives everything it missed, in the order it was sent.
  7. 6 · Ack deletes the recordAfter showing the notification the client sends the ack, and that row is removed. The table returns to empty instead of growing forever.

WebSocket hibernationCloudflare can suspend an idle connection and wake it only when something is actually sent, so a thousand waiting devices do not cost a thousand running processes.

Next: the seven calls that make this path happen.

Read the API

How to use it

Seven endpoints, and only one of them sends anything

Everything below is the complete interface. One call comes from your backend (/v1/push), five come from the device, and /v1/health exists only to prove the Worker is answering.

Endpoint reference

FastNotifications HTTP API: method, path, what each endpoint expects for authentication, and what it does
MethodPathAuthWhat it does
GET/v1/healthNoWorker liveness and server timestamp.
POST/v1/devices/registerNoBind a device id to a user email.
POST/v1/pushBearer YOUR_API_KEYDeliver to a user's registered devices, or queue the row.
GET/v1/notifications/pendingX-User-EmailUnacknowledged notifications waiting for one user.
POST/v1/notifications/:id/ackNoConfirm the client showed it, then permanently delete the row.
DELETE/v1/devices/:deviceIdX-User-EmailUnregister a device.
GET/v1/ws?userId=…&deviceId=…Registered deviceThe WebSocket stream itself, over wss.

Authorization: Bearer YOUR_API_KEYthe server-to-server password, sent as a header. Only /v1/push needs it, because only that call is allowed to create a notification.

X-User-Emaila header the device sends to say whose queue it is reading. The email is the account key: it is hashed into the user id the Durable Object is addressed by.

Send a notification

One request carries the whole payload: who receives it, what to show, and any extra data the app wants. The response tells you which of the two outcomes happened.

POST /v1/push
curl -X POST https://YOUR-DOMAIN.workers.dev/v1/push \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "title": "New order #1042",
    "body": "An order arrived while you were away.",
    "data": { "orderId": "1042", "sound": "loud_alert" }
  }'

Replace YOUR-DOMAIN and YOUR_API_KEY with your own Worker domain and secret.

200 OK
{
  "success": true,
  "status": "delivered",
  "notificationId": "3f2a1c98-6d47-4b0e-9a21-5c8e0d7f4b62"
}

status is "delivered" if a socket was open and the frame went out, "queued" if the row is waiting in D1.

Next: what the device actually receives on its open socket.

See the live stream

Real-time stream

The socket carries exactly one kind of message

A client never has to interpret a protocol. One frame type arrives, it contains everything needed to show a notification, and the only other traffic is a keep-alive.

frame type "push"
{
  "type": "push",
  "id": "3f2a1c98-6d47-4b0e-9a21-5c8e0d7f4b62",
  "title": "New order #1042",
  "body": "An order arrived while you were away.",
  "data": { "orderId": "1042", "sound": "loud_alert" },
  "timestamp": 1726756800000
}

The id in this frame is the same id you acknowledge later, so the delete always matches the row that was shown.

GET /v1/ws
wss://YOUR-DOMAIN.workers.dev/v1/ws?userId=USER_ID&deviceId=DEVICE_ID

  →  "ping"      // client, every 20-30s while idle
  ←  "pong"      // worker, connection is still healthy

Send a WebSocket ping frame or the text "ping"; the Worker answers "pong".

Frameone complete message on a WebSocket. Here every frame is JSON with a type field, and the only type the server sends is push.

Ping / pong heartbeata two-way check that costs almost nothing. It proves the path is still open, so a dead connection is noticed by the client instead of by a missing notification.

While nothing is being sent, the Durable Object hibernates: Cloudflare keeps the connection registered but stops charging for a running process. A push wakes it, the frame goes out on the socket that already exists, and it sleeps again.

The same wake, in words

  1. 1The socket stays registered while the object idles. No process runs, so nothing is billed.
  2. 2A POST to /v1/push names that user, which starts the object again on the first request.
  3. 3The frame is written to the connection that never closed, so the phone shows it at once.
  4. 4The object idles again. The next push repeats the same four steps.
A hibernating WebSocket over timeA vertical line stays connected while the object idles (dashed, un-billed), wakes for one push, writes a frame, and idles again — the same shape as a utility pole keeping its line.t0t1connectthe socket registers — one request opens itwake + framea push starts the object; the frame ridesthe socket that never closedidle · registered · not billedidle again · next push repeatsdevice
Figure 3. A line stays on the crossarm whether or not anyone is on it, and the spare is coiled at the side. A hibernating socket is the same object: registered, idle, and one request away from carrying traffic.

Next: the client side that keeps that socket alive.

See the Android client

The reference client

A Kotlin client that stays connected

test-app-kotlin is a complete runnable app, not a snippet. It is the reference for the reconnect behaviour the backend expects.

What the sample app solves

A socket in an Android app dies when the screen locks or the activity is closed. These four pieces are what make it survive that.

  • Stays running in the backgroundA sticky foreground service declares itself as data-sync work, so Android keeps the socket alive after you leave the screen.
  • Reconnects itself, gentlyOn failure it waits, retries, and doubles the wait each time, so a long outage does not turn into a burst of requests.
  • Actually makes noiseA high-priority notification channel with its own loud sound and vibration pattern, because a silent notification is not a notification.
  • Catches up on openThe moment the socket opens it fetches pending notifications, so a reconnect flushes the queue without the user doing anything.

Foreground servicean Android process the system keeps running because it is visibly listed as ongoing work. Without it, the socket is closed as soon as the app is backgrounded.

OkHttpAndroid's standard HTTP client. Its WebSocket support is what provides pingInterval and automatic reconnect above.

Open test-app-kotlin
PushNotificationService.kt
private val client = OkHttpClient.Builder()
    .pingInterval(20, TimeUnit.SECONDS)     // keep-alive while the socket is idle
    .retryOnConnectionFailure(true)         // exponential reconnect
    .build()

fun connect(userId: String, deviceId: String) {
    val request = Request.Builder()
        .url("wss://YOUR-DOMAIN.workers.dev/v1/ws?userId=$userId&deviceId=$deviceId")
        .build()

    client.newWebSocket(request, object : WebSocketListener() {
        override fun onOpen(socket: WebSocket, response: Response) {
            fetchPendingNotifications()     // recover anything queued offline
        }

        override fun onMessage(socket: WebSocket, text: String) {
            val item = parseNotification(text)
            showNotification(item)          // high-priority channel
            acknowledge(item.id)            // deletes the D1 row
        }
    })
}

Trimmed to the connection and recovery path. The full service is in the repository.

Next: the six steps that put this Worker on your own Cloudflare account.

Deploy it yourself

How to deploy

Six steps from a clone to a live endpoint

No account signups and no external project to create. Every value below is a placeholder; your own database id and API key never go in the repository.

  1. 1Clone the repositoryThe Worker, the migrations and the Android sample are all in it.
  2. 2npm installNeeds Node 18 or newer.
  3. 3Create a D1 database and paste its id into wrangler.tomlThis is where the offline queue lives.
  4. 4Apply the migrations, locally first then remoteCreates the schema every endpoint above reads and writes.
  5. 5Set the API_KEY secretThe value /v1/push will expect in its Bearer header.
  6. 6Deploy the WorkerYou get a https://YOUR-DOMAIN.workers.dev endpoint immediately.
terminal
git clone https://github.com/FastHand-Studio/FastNotifications.git
cd FastNotifications
npm install

npx wrangler d1 create notifications-db
# paste the returned database_id into wrangler.toml under [[d1_databases]]

npx wrangler d1 migrations apply notifications-db --local
npx wrangler d1 migrations apply notifications-db --remote

npx wrangler secret put API_KEY
npm run deploy

wranglerCloudflare's command-line tool. It is how you create the database, set secrets and publish the Worker.

secreta value stored by Cloudflare and injected at runtime, so it never appears in your code or your repository.

Next: the two links that start all of this.

Get the repository

How to get it

Take the code

Two ways in: browse it on GitHub, or pull the whole default branch as a zip. Nothing is hosted for you, and nothing phones home.

https://github.com/FastHand-Studio/FastNotifications

The zip is built from the main branch, which is the repository default.

Stack and licence

Five pieces of infrastructure, one licence

Everything here is either Cloudflare's own platform or a language runtime. There is no queue service, no push vendor and no database host to pay separately.

Cloudflare Workers
Runs the HTTP API at the edge, close to whoever is being notified.
Durable Objects
Gives each user one addressable process that can hold their WebSocket open.
Cloudflare D1
Stores devices and pending notifications in the same account.
TypeScript
One language from the API through to the client types.
Kotlin
The Android sample, so the reconnect behaviour is proven on a real device.
MIT License
Use it commercially, fork it, ship it.

MIT licensed, built by FastHand Studio. Bugs and pull requests go to the repository, not to an inbox.

Next: the other things the studio has published, on the same stack and terms.

Browse all products