All articles
  • WebRTC
  • Real-time Systems
  • PWA
  • Open Source

YACS: Peer-to-Peer Chat That Falls Back Gracefully

A chat app that needs no phone number or address book. How YACS sends each message directly between devices when it can, relays or queues it when it can't, verifies who's on the other end, and keeps working offline.

Adil11 min read

Every mainstream chat app starts the same way: give us your phone number, then let us read your address book. That is a fine trade for talking to family. It is a poor one for talking to someone you met at a meetup ten minutes ago, a seller on a classifieds site, or a stranger you may never speak to again. You want a conversation, not a permanent link between your identities.

YACS (Yet Another Chatting Software) is my answer to that. I started it in 2019, wrote most of the first version during the 2020 lockdown, and have rebuilt much of it since. It is a messaging app that runs in the browser and installs like a native one. You share a link or a QR code, the other person opens it, and you are talking. No phone number, no contact list. It is open source under Apache-2.0 and ships as a single Docker image you can run yourself.

This article is less a feature list than an account of one design decision and everything that follows from it: in a one-to-one conversation, messages should go directly between the two devices whenever they can, and the server should only step in when they can't.

What it does

  • No sign-up wall. Opening the app makes you a guest with a generated name. You can sign in with Google later to keep the account, and the guest becomes a regular user. Guests inactive for 30 days are deleted.
  • Connect by link or QR code, or by username. Nothing asks for your contacts.
  • Nearby, if you opt in. You can share your location to find people close by and filter them by labels. Discovery switches itself off 14 days after you last refreshed your location, so you are not findable forever because you tried it once.
  • Messages, photos, files, and voice and video calls, one-to-one and in groups.
  • It behaves like an app. It installs as a PWA, receives push notifications, rings for incoming calls, and keeps working through a flaky connection.

Three ways a message can travel

Open a direct conversation and a small badge in the header tells you how your messages are currently getting there. It shows one of three states, and they are the core of the design.

  • P2P. The message goes straight to the other device over a WebRTC data channel. The server is not on the path.
  • Relay. No direct connection was possible, so the server passes the message on live over a WebSocket, without storing it.
  • Stored. The recipient is offline, so the server keeps the message in MongoDB until their device comes back and confirms it has it. Then the copy is deleted.

The badge is there because I think users deserve to know where their words are going. It also kept me honest while building: every time I saw "Stored" where I expected "P2P", there was a bug to find.

Envelopes, addressed to devices

Everything that moves in a direct conversation is an envelope: a new message, a status change (delivered, seen), or a deletion. Envelopes are Protocol Buffers messages, defined once in a shared package and used by the browser, the service worker and the server alike.

packages/dto/proto/v1/envelope.proto (abridged)typescript
message Envelope {
  string id = 1;
  string conversation_id = 2;
  string from = 3;        // overwritten by the server when relaying
  string created_at = 4;
  oneof payload {
    EnvelopeMessage message = 5;
    EnvelopeStatus status = 6;
    EnvelopeDelete delete = 7;
  }
}

// Relay request from the sender's device.
message EnvelopeSend {
  Envelope envelope = 1;
  repeated string delivered = 2;  // devices that already got it peer to peer
}

The important word is device. People use the same account on a phone and a laptop, so a message isn't delivered to a person; it is delivered to each of their devices, and to the sender's other devices too, so their history stays in step. One device might be reachable directly while another is asleep in a pocket.

Sending an envelope works like this:

  1. The sender asks the server which devices are in the conversation and which are online right now.
  2. For each online device, it opens a direct WebRTC channel (or reuses one), sends the envelope, and waits for an acknowledgement.
  3. For every device that didn't acknowledge, it hands the envelope to the server, listing the devices that already have it.
  4. The server tries to push it live to each remaining device and waits up to five seconds for an acknowledgement. Any device that doesn't answer gets the envelope queued.
  5. When a device reconnects, it pulls its queue in batches of 200, stores the envelopes locally, and acknowledges them. Only then does the server delete them.

That gives each device exactly one of the three paths, and the badge reports which one was used.

Delivering twice must be harmless

Any system that retries will sometimes deliver the same thing twice. An acknowledgement can be lost after the envelope arrived, or a device can reconnect halfway through a sync. Rather than trying to prevent duplicates, YACS makes them harmless.

  • The queue has a unique index on device and envelope id, and envelopes are inserted with an upsert. Queuing the same envelope twice leaves one row.
  • Message ids are created on the sending device, so a retried message carries the same id and the receiver recognises it.
  • Status only moves forward. A device that already shows "seen" ignores a late "delivered". Status changes are also batched for 300 ms, so scrolling through a long conversation sends one "seen" envelope instead of fifty.

Who is on the other end?

A direct connection raises a question the server would normally answer: when a device connects and says "this is from Riley", how do you know? WebRTC encrypts the channel, but encryption tells you nothing about who opened it.

YACS answers it with short-lived tickets. When the sender asks for the list of online devices, the server signs a ticket for each one, stating who is sending, from which device, and which peer it is meant for. The sender attaches the ticket to what it sends. The receiver asks the server to verify the ticket, and accepts the envelope only if:

  • the ticket was issued for this receiver's own peer connection, not someone else's;
  • the two users actually share a direct conversation;
  • the envelope is for a direct conversation the receiver has, and comes from the other participant or from one of the receiver's own devices.

The receiver caches verified tickets, so this costs one lookup per peer rather than one per message. The server never sees the message itself, only the question "is this ticket real?".

Sending while offline

A message you type on a train should still arrive. Outgoing envelopes are written to an outbox in IndexedDB before anything is sent, and removed only once they have been delivered or handed to the server. While the app is open, failed sends are retried after 2, 5, 15, 30 and then 60 seconds, and the outbox is flushed again as soon as the browser reports it is back online.

If you close the app before that happens, the service worker takes over. The app registers a Background Sync task, and when connectivity returns the browser wakes the service worker, which reads the same outbox and posts the envelopes to an HTTP endpoint that does exactly what the WebSocket route does. Background Sync is only available in Chromium-based browsers; elsewhere the in-app retries still apply.

Photos and files

A photo is compressed on the sending device first. It then goes peer to peer only if every recipient device is reachable directly and the image is within the size limit. If any device can't be reached, the photo is uploaded instead, the server makes a thumbnail, and it is delivered like any other stored message. A photo is never sent half peer to peer and half through the server.

Files are different, because they can be large and a mobile connection will drop halfway through. For these I wrote a small package, @yacs/webshare, that does resumable transfer over any reliable data channel. The file is cut into 16 kB chunks, and the receiver drives the transfer by asking for blocks of 64 chunks at a time and ignoring anything that arrives out of order. If the connection stalls or drops, the receiver reconnects with backoff and asks for the next chunk it is missing. Nothing already received is sent again.

Because the bytes come from the sender's device, the sender has to be online for a transfer to happen. The server only records which device is offering the file and issues tickets, the same way it does for messages, so only a member of the conversation can download it.

Calls

Calls use the same peer connection as messages and files: one PeerJS peer per device, with separate channels for each job. Most of the time two browsers can reach each other directly, with help from public STUN servers. Some networks, such as strict corporate firewalls and some mobile carriers, won't allow that, and the call needs a TURN server to relay the media.

A TURN server is happy to relay anyone's traffic, so its credentials shouldn't be handed out permanently. YACS gives each user temporary credentials, in the format coturn checks with a shared secret: the username is an expiry time plus the user id, and the password is an HMAC of that username.

api/src/call/call-handler.tstypescript
const username = `${Math.floor(Date.now() / 1000) + turn.ttl}:${ctx.state.user.id}`;
const credential = createHmac("sha1", turn.secret).update(username).digest("base64");
servers.push({ urls: turn.urls, username, credential });

The rest is the work every calling app has to do. Calls ring for 45 seconds. If the recipient's app isn't open, they get a push notification. Answering on one device stops the ringing on the others, and a missed or declined call leaves an entry in the conversation.

Where the server still matters

It would be easy to oversell this, so it's worth being precise about what "peer to peer" does and doesn't mean here.

  • Groups go through the server. Peer-to-peer delivery is for direct conversations. Group messages are sent over the WebSocket and stored in MongoDB, and the badge says so.
  • This is not end-to-end encryption. A peer-to-peer channel is encrypted between the two devices, but when a message is relayed or stored, the server handles it in readable form. If you need guarantees against the server operator, use a protocol designed for that, such as Signal's.
  • The server is still essential. It handles accounts, presence, setting up the peer connections (the PeerJS signalling server runs inside the same Node.js process), tickets, push notifications and the queue. Going peer to peer doesn't remove the server; it removes the server from the path of the message.

Being self-hosted is what makes those trade-offs acceptable. When the server is yours, "the server can read relayed messages" means you can, on your own machine.

Running it

YACS needs MongoDB and Redis and is configured with environment variables. The only required one is APP_KEY, which signs sessions and tickets. Google sign-in and TURN are optional: leave them empty and the Google button is hidden and calls use STUN only.

Minimal setupbash
# Generate the one required secret
openssl rand -base64 48

# Then run the image with APP_KEY, DB_URL (MongoDB) and CACHE_URL (Redis) set.
# Set COOKIE_SECURE=true when serving over HTTPS.

The image builds the app, the API and the shared packages, then ships only the API's production dependencies on a slim Node.js base. It runs as a non-root user and has a health check, so it fits behind an ordinary reverse proxy.

What I took from it

The idea I started with was "peer to peer is more private". The idea I ended with was simpler: every message should take the most direct path available at that moment, and fall back to the next one without the user having to care. Most of the code isn't about WebRTC at all. It's about the fallbacks: outboxes, queues, acknowledgements, retries, and making a second delivery harmless. That's true of most distributed systems, and a chat app turns out to be a small, very honest one.

Further reading