- Go 78.8%
- HTML 12%
- JavaScript 3.1%
- CSS 3%
- Shell 1.2%
- Other 1.8%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
- "Interested in meeting" and the browse filter offer Women / Men / Non-binary people; profiles say "Interested in women and men" (or "anyone"). - "Children (wanted)/(have)" become "Plans for children" and "Children". - Rewrite the two-way matching hint and the browse filter hint. - Conversations show the other person's name instead of "Them". - "Smokes" -> "Smokes regularly"; "Trade / vocational" -> "Vocational qualification". - Email no longer says "1 things in common"; validation names fields in words. - French/Spanish: matching catalogue updates; editor legend addresses the member. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
| .github/workflows | ||
| ci | ||
| cmd/longform | ||
| helm/longform | ||
| internal | ||
| k8s | ||
| .dockerignore | ||
| .env.example | ||
| .gitignore | ||
| Dockerfile | ||
| go.mod | ||
| go.sum | ||
| justfile | ||
| README.md | ||
Longform
A dating site built around writing. There's no swiping. People write long-form profiles in sections, add up to six photos and some personal details, and browse a list ranked by what they have in common.
The core rule: a first message to someone must reach the minimum length they chose: anything from 5 words up to half the words in their own profile, and 100 words (INTRO_DEFAULT_WORDS) unless they choose otherwise. Someone who wrote 600 words can ask for up to 300; someone who wrote 150 words gets at most 75, whatever they chose. Quoted lines don't count. Once they reply, the conversation opens and there's no minimum.
Features
- Editing: reorder profile sections and add more without saving. Reorder and rotate photos, and choose each photo's focus (click the spot, or pick a preset without JavaScript) so the 4:5 thumbnail crops around it. Re-rendered photos get a new id, so immutable photo caching stays correct. Introduction drafts autosave to your account, follow you between devices, and are deleted when sent or after 30 days.
- Long-form profiles: up to 8 written sections with suggested or custom headings, interests, and optional stats (relationship style, children, smoking, drinking, religion, politics, education, languages, height, location). A profile is listed only once it has
MIN_PROFILE_CHARS(default 600) characters of writing, and you can't write to anyone until your own profile is listed. - What you have in common: every profile and browse card shows shared interests, compatible stats, real differences (e.g. one of you wants children and the other doesn't) and distinctive shared words. These are weighted by inverse document frequency, and highlighted in the other person's writing.
- How words are compared: each profile's language is detected (English, French, Spanish, Russian, Swedish, Norwegian) and stemmed with Snowball, so "climbing", "climbs" and "climbed" match. A curated stopword list filters filler words. Names like "Ursula Le Guin" or "Peak District" are recognised as whole phrases.
- Learning from behaviour: ranking also learns from what you engage with. Terms common to profiles you've saved or written to are blended into your ranking at half weight.
- Reindexing: when the tokenizer changes, stored terms are rebuilt automatically on startup, once, under an advisory lock.
- Search what people wrote: Postgres full-text search over profile writing and interests, using a stored generated
tsvectorcolumn with a GIN index that Postgres keeps current itself. Queries use web-search syntax ("Le Guin",climbing OR bouldering,-golf) with stemming, rank by relevance, and show highlighted snippets. The snippets are escaped before highlighting, so profile text can't inject markup. - Distance search: members can share an approximate location from their browser (opt-in; rounded to about 1 km before it's stored, and no third-party geocoder is involved). Browse can then filter by "within N km" and sort by nearest. Distances are shown in buckets ("under 5 km away", then the nearest 5 km), so repeated measurements can't be used to pinpoint anyone. The query uses an indexed bounding box and then an exact haversine distance.
- Landing page: for logged-out visitors, with an invented sample profile (never real members' text), a practice box that runs the real word counter without sending or saving anything, how it works, what we don't do, "free while we launch" (UK-wide), safety and privacy, and an FAQ. It has a meta description, link-preview tags and a canonical URL.
robots.txtandsitemap.xmloffer only the public pages. Landing and sign-up page views are counted inlongform_events_total(landing_view,signup_view) without cookies. SetOPERATOR_NAMEso the FAQ can say who runs the site. - Campaign codes: links like
/?ref=lrb-jantell you which adverts, articles and events bring people. Codes are 1–32 lower-case letters, digits,-or_; anything else is ignored. The code travels in the URL from the landing page to the sign-up form (never in a cookie), and the new account records it inusers.signup_ref. Visits are counted per code per day inref_daily, at most once per network per code per day (keyed-hash dedupe via the rate-limit table), skipping crawlers and link previews. Moderators see visits, sign-ups, surviving accounts and written profiles per code at/admin/refs. The privacy policy says all this. - Browse without swiping: a readable list sorted by most in common, recently active, newest or longest, with filters for gender, age and location. Matching is mutual for gender and age: you only see people interested in your gender whose preferred age range includes you, and vice versa. Your own age range is your default browse filter, and introductions to people whose range excludes you are refused with an explanation. You can save profiles to read later.
- Introductions: the composer shows the profile next to your draft, with a live word count against the requirement. Members set their own requirement with a slider in the profile editor, whose range grows and shrinks as they write; a stored choice is capped at half their current word count when used, and members who never touch it follow the default. The server enforces the requirement, ignores whitespace padding and rejects heavily repetitive text. You can quote passages from their profile (a Quote button on each paragraph, or Quote selection) to reply to something specific. Quoted lines render as blockquotes and don't count towards the minimum, so quoting can't be used to pad. You get one introduction per person; the recipient can reply (which opens the conversation) or decline. New messages arrive live over Server-Sent Events: a Postgres trigger fires
pg_notify, each replica holds one LISTEN connection and fans events out to its streams, and each stream re-reads authorised data from the database. Streams resume withLast-Event-ID, and a heartbeat also catches anything missed during reconnects. If EventSource isn't available, the page falls back to polling. Unread counts appear in the nav. You can archive a conversation (a new message brings it back), end it for both people (withdrawing a pending introduction), or delete it for yourself; once both people have deleted it, the messages are erased. - Email: sign-up sends a confirmation link (48h, single use), and you must confirm your address before you're listed or can write to anyone. "Forgot password" sends a one-hour, single-use reset link; resetting signs you out everywhere. Only hashes of tokens are stored, and the forgot-password page gives the same response whether or not an account exists. Mail goes through a transactional outbox in Postgres (
FOR UPDATE SKIP LOCKED, safe across replicas) with exponential-backoff retries, so a slow or failing provider never blocks a request. The provider is Postmark in production and Mailpit locally. - Email upkeep: Postmark bounce and spam-complaint webhooks suppress notification emails to dead or complaining addresses, and the member is asked to update their address. Changing your email address requires your password and a click on a link sent to the new address, and sends a notice (with the new address partly masked) to the old one.
- Introduction notifications: when someone writes you an introduction you get an email saying who wrote it, how long it is and how much you have in common, with a link to read it. The message itself isn't in the email, so it isn't copied into mail providers' storage. Notifications are throttled to one an hour unless you've visited since, can be turned off in Settings, and carry RFC 8058 one-click
List-Unsubscribeheaders. The unsubscribe page in the email asks for confirmation, so link scanners can't trigger it. - Reply notifications: when a message is still unread after
REPLY_NOTIFY_DELAY_MINUTES(default 10), the other person gets an email. There's one email per conversation until they've read it, several conversations are combined into a single digest, and the first reply to your introduction gets its own wording. Like introduction emails, they have a separate opt-out and one-click unsubscribe, and never include the message text. A partial index onconversations.notify_due_atkeeps the 30-second worker cheap, andSKIP LOCKEDclaiming makes it safe across replicas. - Moderation:
- Roles: members, moderators and admins. Roles are granted only from the command line (
longform role <email> moderator), so there's no web path to privilege escalation. - Tools: moderators get a report queue (including the conversation, when a report is filed from one), photo pre-moderation (
PHOTO_PREMODERATION, on by default), member search, and timed suspensions or permanent bans with a reason that's emailed to the member. Every action goes into a per-member audit log. - Limits: moderators can't act on themselves or on other staff; only admins can.
- Effect of suspension or ban: the member's sessions end, and they disappear from browse, profiles, notifications and messaging. Suspensions lapse automatically when they expire.
- Roles: members, moderators and admins. Roles are granted only from the command line (
- Legal and data rights: terms of service and a privacy policy that describe what the code actually does (no stored IP addresses (rate limits use keyed hashes), no tracking, strictly necessary cookies only, 30-day email retention). Sign-up records agreement and the terms version. "Download my data" exports a ZIP with your account, profile, photos, conversations, saved, blocked and reported people, and moderation actions. Have both documents reviewed by a lawyer for your jurisdiction before launch; set
OPERATOR_NAMEandCONTACT_EMAIL. - Photo storage: every photo is stored as three sizes: full (up to 1600px), a 4:5 thumbnail cropped around its focal point, and a small avatar. Each size is stored as AVIF, WebP and JPEG, encoded in pure Go (WebAssembly builds of libaom/libwebp, so the binary stays static). Uploads store JPEGs immediately (about 0.4 s), and a background worker that wakes on upload adds WebP and AVIF in parallel within seconds. The same URL serves the best format the browser accepts (
Vary: Accept), cached immutably per photo id. Files live in Postgres by default, or in any S3-compatible bucket (PHOTO_STORAGE=s3). They're streamed by the app, or withPHOTO_DELIVERY=redirecthanded out as short-lived presigned URLs, so photos stay members-only either way. A background worker generates missing renditions, moves existing photos into object storage, and deletes orphaned objects; deletions are queued by a database trigger, so nothing is leaked. The local chart bundles SeaweedFS to exercise the S3 path. - Accessibility: audited with a checker script across every page. All pages pass: one
h1each, no skipped heading levels, every control labelled, alt text on images, no duplicate ids, and amainlandmark. Both themes meet WCAG AA contrast. There's a skip link, visible keyboard focus, labelled landmarks,aria-liveupdates for new messages and counters, reduced-motion support, and filters that collapse on narrow screens. - Languages: the interface, emails and in-page script text are available in English, French and Spanish. The language comes from the member's setting, then a language cookie (footer switcher), then the browser's
Accept-Language. Distances are shown in kilometres or miles, defaulting by region (miles for the UK and US) and changeable in Settings. Catalogues are JSON keyed by the English text, so anything missing falls back to readable English.TestTranslationsCompleteextracts every key from templates and Go code and fails if a catalogue is missing one, has stale ones, or changes a translation's HTML tags or format verbs. To add a language, addlocales/<code>.jsonand list it ini18n.Locales. The terms and privacy policy remain English-only, with a translated notice saying so. - Installable app and push: a web app manifest and icons make Longform installable. The service worker shows an offline page and caches static assets, but never caches pages, so no profiles or messages are stored on the device. Members can turn on notifications per device in Settings. These use standard Web Push (VAPID keys generated once and stored in the database; RFC 8291 encryption), follow the same email-notification preferences and say who wrote, never what. Pushes still arrive if email to the address has bounced. Push endpoints must be HTTPS at the known browser push services (
PUSH_ALLOWED_HOSTSto override), because the server POSTs to them and arbitrary URLs would allow SSRF. Dead subscriptions are removed automatically. - Unguessable ids: anything that appears in a URL (members, photos, conversations, reports) is addressed by a random 22-character public id (16 random bytes, base64url). Internal sequential keys never leave the server, so URLs don't reveal member counts or growth, and a future access-control bug couldn't be exploited by counting through ids. Photo object-storage keys use public ids too, because they appear in presigned URLs. A member requesting many unknown ids triggers a warning log and the
LongformIDProbingalert. - Spam and scams (
internal/spam): checks run on a cleaned copy of the text (compatibility-normalised, invisible characters removed, Cyrillic/Greek look-alike letters mapped to Latin), so tricks like zero-width spaces inside "WhatsApp" or Cyrillic letters in "Telegram" don't get through; what people wrote is stored unchanged.- Contact details: links, email addresses, phone numbers, usernames for other apps, and crypto wallet addresses are refused in introductions and profiles. An app name on its own ("I'm off Instagram") is fine; an app with a username or an invitation isn't. Once people are talking they can share anything, but a message from the other person that contains contact details shows a scam warning.
- Copy-paste introductions: an introduction that shares 60% or more of its three-word sequences with one the sender has sent in the last 30 days is refused (quoted lines ignored on both sides).
- Sign-up: a hidden honeypot field, a signed "form served at" token that must be at least
SIGNUP_MIN_SECONDS(default 3) old, and a built-in list of throwaway inbox domains (extend it withBLOCKED_EMAIL_DOMAINS, which also applies to email changes). Blocked attempts are counted inlongform_events_total(signup_honeypot,signup_too_fast,signup_disposable_email,intro_contact_blocked,intro_duplicate_blocked,profile_contact_blocked).
- Safety and privacy: argon2id passwords, server-side sessions (only hashed tokens are stored), CSRF protection via
http.CrossOriginProtection, strict CSP, login and sign-up rate limits, a daily introduction limit, block, report, pause profile, and full account deletion. Photos are re-encoded to JPEG with EXIF orientation applied, which strips GPS and other metadata, and are served only to signed-in members who haven't been blocked by the owner.
Architecture
| Language | Go (stdlib net/http and html/template, no framework) |
| Database | PostgreSQL 16 via pgx/v5, with embedded SQL migrations guarded by an advisory lock |
| Frontend | Server-rendered HTML plus about 150 lines of vanilla JS (progressive enhancement; everything works without JS) |
| Image | Static binary on distroless, about 18 MB |
| Deploy | Helm chart and kind for local; HPA-ready for production |
Built to scale out:
- Stateless app pods. Sessions and photos live in Postgres, with no local disk, so replicas scale horizontally (the old uploads PVC is gone).
- Ranking in a single SQL query. A
profile_termsinverted index plus aterm_dfmaterialized view (refreshed every 2 minutes by one replica holding an advisory lock) score shared words. Candidates are capped at the 3,000 most recently active matches before scoring. - Shared code. Commonality scoring in Go (
internal/match) mirrors the SQL ranking weights.
cmd/longform entrypoint: serve | migrate | seed [n]
internal/core domain types and option labels
internal/policy intro-length rule (the core mechanic)
internal/textutil prose measurement and tokenization
internal/match commonality and IDF weighting
internal/imaging decode, orient, resize, re-encode photos
internal/store Postgres data access
internal/db pool and migrations (migrations/*.sql)
internal/web handlers, middleware, templates, static assets
helm/longform chart (bundles Postgres for local use)
Running locally
Requires Go 1.25+, docker/podman, kind, helm and just.
just up # create kind cluster, build image, deploy app + Postgres
kubectl exec deploy/longform -c app -- /longform role you@example.com admin # moderation access
just seed # optional: 40 demo profiles (demo1@example.com … / password longform-demo)
just open # http://localhost:8080
just mail # Mailpit inbox at http://localhost:8025 — every email the app sends
just smoke # end-to-end smoke test (verifies accounts via Mailpit's API)
Development:
just test # unit tests
just test-integration # full HTTP + Postgres test against the cluster's database
just db-forward # in one terminal…
just dev # …and run the server locally with `go run`
Operations
-
Metrics: Prometheus metrics on
:9090/metrics(METRICS_ADDR). This port isn't exposed by the public Service or Ingress; a separatelongform-metricsClusterIP Service exists for scraping. Metrics cover requests and latency by route pattern, panics, product events (sign-ups, introductions, messages, reports), the email outbox, moderation queues, scheduled reply notifications, the DB pool and DB reachability. Setmetrics.serviceMonitor.enabledandmetrics.prometheusRule.enabledwith the Prometheus Operator to get scraping and alerts: down, 5xx rate, panics, latency, database unreachable, email backlog and failures, moderation backlog, pool saturation, and missing backups. -
Errors: logs are JSON on stdout. Panics are logged with stack traces and counted; ship logs to your aggregator and alert on
level=ERROR. -
Backups: a nightly
pg_dumpCronJob (backup.*values) writes verified custom-format dumps to a PVC and keeps 14 days. Useful commands:just backup-nowtakes a backup now.just backupslists them.CONFIRM=yes just restore <file>restores one.
On a managed database, also use the provider's point-in-time recovery, and copy dumps off-cluster.
-
CI (
.github/workflows/ci.yml): gofmt, vet, race-enabled unit and integration tests against Postgres; Helm lint and kubeconform schema validation for local and production values; a Secret layout check; an image build; and a full kind deployment with the smoke test and a backup. -
Production config check:
just check-prodvalidatesvalues-prod.yamlagainst the cluster's API server with a server-side dry run, applying nothing.
Capacity
Measured on 2026-11-15 in the local kind cluster (8-core laptop) against a scratch database with 5,000 seeded profiles, with the load generator inside the cluster and CPU read from each pod's cgroup:
| Page | App CPU / request | Postgres CPU / request | Throughput, one replica (16 clients) |
|---|---|---|---|
| Browse (in common / newest / search) | 16–22 ms | 43–57 ms | 80–110 req/s |
| Browse (nearest, 50 km) | 14 ms | 12 ms | 230 req/s |
| Profile | 4 ms | 2.4 ms | 800 req/s |
| Conversation | 3 ms | 2.9 ms | 500 req/s |
| Inbox | 1.6 ms | 1.8 ms | 1,400 req/s |
| Landing (logged out) | 1.9 ms | — | 2,000 req/s |
Live-update streams are cheap: 1,000 open streams used ~24 MiB and 16 ms/s of app CPU, plus ~60 ms/s of Postgres CPU for their 25-second access re-checks.
Rule of thumb. An active user (per minute: one browse, three profiles, the inbox, two conversation views, one open stream) costs about 0.7 ms/s of app CPU and 1.2 ms/s of Postgres CPU. At 60% utilisation that is ~800 simultaneously active users per app core and ~500 per Postgres core, so Postgres is the first limit: two 1-core replicas and a 4-core Postgres serve ~1,500–2,000 people using the site at the same moment. Simultaneous users are typically a few percent of members.
Scaling notes
- Browse scores up to 3,000 matching candidates per request, so its cost grows with the membership until that cap; re-measure as the site grows.
- Each replica opens up to
DB_MAX_CONNSconnections (10 invalues-prod.yaml); keepmaxReplicas × DB_MAX_CONNSunder Postgres'smax_connections, or add PgBouncer. - Every connection sets
plan_cache_mode = force_custom_plan. Without it, Postgres switched the browse query to a generic plan after a few runs and it cost ~1.1 s of database CPU per request. - These are laptop numbers; repeat the test on production hardware before relying on them.
Configuration
| Variable | Default | Meaning |
|---|---|---|
DATABASE_URL |
local Postgres | Connection string |
INTRO_DEFAULT_WORDS |
100 |
Minimum words in a first message to someone who hasn't chosen (always capped at half the words in their profile) |
MIN_PROFILE_CHARS |
600 |
Writing needed to be listed / to write to others |
INTROS_PER_DAY |
10 |
New conversations a person can start per 24h |
SIGNUP_MIN_SECONDS |
3 |
Sign-up forms submitted faster than this are treated as bots |
BLOCKED_EMAIL_DOMAINS |
— | Extra throwaway email domains to refuse (comma-separated) |
MAX_UPLOAD_MB |
15 |
Photo upload limit |
SESSION_DAYS |
30 |
Session lifetime |
SECURE_COOKIES |
false |
Set true behind HTTPS |
MIGRATE_ON_START |
true |
serve applies migrations (the chart uses an init container instead) |
DB_MAX_CONNS |
20 |
Pool size per replica |
METRICS_ADDR |
:9090 |
Internal Prometheus listener (off to disable) |
TRUSTED_PROXIES |
0 |
Reverse proxies in front of the app; picks the real client from X-Forwarded-For (the chart sets 1 when ingress is enabled) |
PUSH_ALLOWED_HOSTS |
browser push services | Comma-separated hosts (leading . for subdomains) allowed as Web Push endpoints |
RATE_LIMIT_SCALE |
1 |
Multiplies all rate limits (the local chart uses 100) |
OPERATOR_NAME / CONTACT_EMAIL |
Longform / hello@longform.local |
Named in the terms and privacy policy |
PHOTO_STORAGE |
db |
db (Postgres) or s3 (S3-compatible bucket) |
PHOTO_DELIVERY |
proxy |
proxy (app streams photos) or redirect (presigned object URLs; s3 only) |
S3_ENDPOINT / S3_BUCKET / S3_REGION |
Bucket location, e.g. s3.eu-west-2.amazonaws.com (R2, B2, SeaweedFS, MinIO also work) |
|
S3_ACCESS_KEY / S3_SECRET_KEY |
Credentials (the secret goes in the Helm Secret as s3SecretKey) |
|
S3_USE_SSL / S3_PATH_STYLE |
true / false |
Path-style URLs for most self-hosted servers |
PHOTO_PREMODERATION |
true |
New photos need moderator approval before others see them |
REPLY_NOTIFY_DELAY_MINUTES |
10 |
Unread replies wait this long before an email (0 in the local chart) |
BASE_URL |
http://localhost:8080 |
Public origin used in email links |
MAIL_PROVIDER |
log |
postmark, smtp (Mailpit) or log (print to stdout) |
MAIL_FROM |
Longform <hello@longform.local> |
Sender; with Postmark it must be a verified sender signature or domain |
POSTMARK_SERVER_TOKEN |
Postmark server API token (in the Helm Secret) | |
POSTMARK_MESSAGE_STREAM |
outbound |
Postmark transactional stream |
POSTMARK_WEBHOOK_USER / POSTMARK_WEBHOOK_PASSWORD |
Basic-auth credentials for /webhooks/postmark; endpoint disabled when empty |
|
SMTP_ADDR |
SMTP relay host:port, e.g. postal.example.com:587 |
|
SMTP_TLS |
auto |
auto (implicit on 465, else STARTTLS if offered), starttls (required), tls (implicit), none |
SMTP_TLS_SERVER_NAME |
relay host | Name checked on the relay's certificate |
SMTP_TLS_CA_FILE |
system roots | PEM bundle for a private CA |
SMTP_TLS_INSECURE_SKIP_VERIFY |
false |
Accept any certificate (test relays only) |
SMTP_AUTH |
plain |
plain, login or cram-md5 |
SMTP_USERNAME / SMTP_PASSWORD |
Credentials; refused over cleartext to non-local hosts | |
SMTP_HELO |
hostname | EHLO name |
SMTP_TIMEOUT_SECONDS |
30 |
Per-message deadline |
For production, use helm/longform/values-prod.yaml: an external database via databaseUrl, TLS ingress, secure cookies, HPA and Postmark (--set postmarkServerToken=…).
Postmark setup
- Create a Server in Postmark and copy its Server API token.
- Under Sender Signatures, verify your domain and add the DKIM and Return-Path DNS records it gives you. Also publish an SPF record and a DMARC policy (
v=DMARC1; p=none;to start). - Set
mail.fromto an address on that domain, andbaseUrlto your public origin. - Deploy with
--set postmarkServerToken=$POSTMARK_SERVER_TOKEN. - Add a webhook in Postmark for Bounce, Spam Complaint and Subscription Change pointing to
https://USER:PASSWORD@your-host/webhooks/postmark, and deploy with matching--set postmarkWebhookUser=USER --set postmarkWebhookPassword=PASSWORD. Hard bounces and complaints then suppress notification emails to that address, and the member sees a banner asking them to change their address. Reactivating the address in Postmark lifts the suppression.
Self-hosted or other SMTP relays (Postal, Postfix, …)
Set mail.provider: smtp and mail.smtp.* in values, and pass --set smtpPassword=…. For a private CA, put the PEM in a Secret and set mail.smtp.caSecret. To check a relay before deploying, send a live test message:
SMTP_LIVE_ADDR=postal.example.com:587 SMTP_LIVE_FROM=hello@example.com SMTP_LIVE_TO=you@example.com \
SMTP_LIVE_USERNAME=… SMTP_LIVE_PASSWORD=… go test ./internal/mail -run TestSMTPLive -v
A 5xx reply to RCPT or after DATA is treated as permanent; everything else (4xx, auth or TLS failures, timeouts) is retried with backoff.
Undeliverable messages (HTTP 422, such as inactive recipients) are marked failed immediately; other errors retry with backoff, up to 8 attempts. Failures stay in email_outbox.last_error.
Not yet built
- Bounce handling for non-Postmark relays; Postal and others have their own webhook formats.
- Age verification beyond the self-declared date of birth (needs an identity provider).