Discovery¶
Purpose¶
Discovery is the query and read-aggregation domain. It answers "what is near me / what matches this query / who is this person" by reading across events, locations, moments, friends, and presence, then shaping a single payload the client renders directly. It never owns write state of its own, it composes other domains' data.
Everything the map, radar, Find tab, and public profile card need is
mounted under /api/v1/discovery. Discovery queries Postgres directly
(raw PostGIS for spatial reads) and reuses three shared pieces rather than
re-implementing them:
platform/taxonomyParseQuery: free-text to(category, tags, freetext).platform/llmsemantic resolver, reached transitively throughlocation.LocationService.Search, which runs the search enricher over Photon rows. See Semantic Resolver.location.LocationServicegeocode: forward-geocodes a city string to a search anchor, reverse-geocodes coords to a city.
Code lives in backend/internal/services/discovery/.
HTTP surface¶
All routes are mounted in backend/internal/services/discovery/routes.go.
The profile read is registered by RegisterPublicRoutes (optional auth);
everything else by RegisterRoutes (JWT-verified group).
| Method | Path | Auth | Handler | Description |
|---|---|---|---|---|
| GET | /discovery/map |
JWT | GetDiscoveryData |
Viewport markers (min_lat, max_lat, min_lng, max_lng, zoom) |
| GET | /discovery/radar |
JWT | GetRadarData |
Nearby people (lat, lng, radius in metres, max 50000) |
| GET | /discovery/locations/:id |
JWT | GetLocationDetail |
Location map-card detail |
| GET | /discovery/search |
JWT | FindByIntent |
Unified NL intent search (q, optional lat/lng/lang/city) |
| GET | /discovery/feed |
JWT | SearchHandler.Feed |
Home feed: full-width moments + ranked events (pill toggle) |
| POST | /discovery/feed/seen |
JWT | SearchHandler.MarkSeen |
Mark moments seen ({moment_ids}) as they scroll past |
| GET | /discovery/search/events |
JWT | SearchHandler.ListEvents |
Event search near the pin (optional start_after/start_before RFC3339 date bounds) |
| GET | /discovery/search/locations |
JWT | SearchHandler.ListLocations |
Place search near the pin (optional price_max, min_rating, friends, awards, has_events, notable, saved filters and sort) |
| GET | /discovery/browse/events |
JWT | SearchHandler.BrowseEvents |
The area's events as ordered, render-ready sections (lat, lng, radius in metres, 1000 to 200000) |
| GET | /discovery/browse/places |
JWT | SearchHandler.BrowsePlaces |
The area's places as ordered, render-ready sections (same params) |
| GET | /discovery/search/users |
JWT | SearchUsers |
User search (q, showMutual) |
| GET | /discovery/pin |
JWT | FindHandler.GetFindLocation |
Read the saved area pill |
| PUT | /discovery/pin |
JWT | FindHandler.SetFindLocation |
Write the saved area pill |
| GET | /discovery/taxonomy |
JWT | TaxonomyHandler.Get |
Localized category + tag vocabulary |
| GET | /discovery/taxonomy/resolve |
JWT | TaxonomyHandler.ResolveQuery |
Free-text query to canonical name + kind |
| GET | /discovery/profiles/:id |
optional | GetUserProfile |
Full aggregated public profile card |
| GET | /discovery/profiles/:id/moments |
optional | GetUserMoments |
Keyset-paginated profile moments tab |
| GET | /discovery/profiles/:id/journal |
optional | GetUserJournal |
Auto-grouped passport journal (trips / days / singles), keyset-paginated |
| GET | /discovery/profiles/:id/atlas |
optional | GetAtlasIndex |
Passport atlas country index |
| GET | /discovery/profiles/:id/atlas/:country |
optional | GetCountryPage |
Atlas country drill (regions / cities / places) |
| GET | /discovery/profiles/:id/atlas/:country/regions |
optional | GetCountryRegions |
Visited admin-1 regions within one country, with GeoJSON boundaries |
Lean vs full profile
GET /users/:userId (see User) returns only the lean
identity card (id, name, username, avatar_url, bio,
is_friend), enough for a mention chip. The full aggregated profile
(recent moments, upcoming/past events, mutual friends) is the
Discovery read at GET /discovery/profiles/:id. :id accepts a user
UUID or a case-insensitive username.
Tap-through map cards (location + event detail sheets, save/dismiss) are a
separate surface owned by the Maps domain, which reads the
canonical Location/Event/Moment rows. Discovery emits the viewport
marker; Maps serves the sheet the marker opens.
Map: zoom-tier strategy¶
GetDiscoveryData branches on zoom so the map stays fast from a
continent-wide view down to a single street. Tier constants and caps live
at the top of backend/internal/services/discovery/service.go.
bbox + zoom
grid clusters, 10° cells
grid clusters, 3° cells
markers 200/200/100, sponsor filter
markers 500/300/150
markers 1000/500/200
IsPriority=true, bypass clusters
events / locations / moments. Friend markers always bypass the cluster path so exact friend positions show at every zoom.At zoom ≤7 a single UNION query snaps every coordinate to a grid cell,
groups by cell, and returns one geo_cluster marker per cell carrying
event / location / moment counts in ClusterCounts. The frontend renders
these directly. At zoom ≥8 the backend sends raw rows and the frontend's
Supercluster library handles the visual grouping.
Per-viewer visibility. Every content marker is scoped to what the caller may actually see, so the map never leaks restricted content:
- Moments (standalone pins + a location's moment badge) apply the moment's
own visibility:
publicto anyone,friendsto accepted friends,close_friendsonly to the author's close friends (closeFriendViewers),privatenever. Standalone moment pins are additionally friend-authored only, gated by theShowFriendMomentspreference, and bounded to a recency window (standaloneMomentMaxAgeHours, 48h) so an old moment doesn't linger as a stale "someone's here now" pin. - Events mirror the feed's visibility (
public+ friend-hostedfriendsevents) plus the viewer's own hosted/joined events, which always show. Events tied to a location ride that location's pin (count + gold overlay); only location-less events get a standalone pin, so nothing shows twice.
Density-adaptive locations. A location normally needs activity (a visible
moment or upcoming event) to appear, ranked friend-activity-first and capped per
zoom. When a viewport is sparse (fewer than sparseLocThreshold active
locations, e.g. a quiet or just-launched city), ListNotablePOIMarkers backfills
nearby POIs up to sparseLocTarget so the map still shows what's around: places
people engaged with first (moments, saves, visits), then prominence, then rating,
so harvested catalog rows fill gaps without crowding out places people use (rows hidden by missed harvests are inactive and never appear). Dense viewports clear the threshold and skip the backfill entirely, so
they stay curated and pay for no extra query. All map queries are pre-filtered by
the PostGIS ST_Intersects index, so the visibility/recency predicates only run
over the viewport candidate set.
Sponsor priority
At city zoom (≤10) only events with sponsorship_tier ≤ 2 are
returned, so the wide view is not drowned by hyper-local sponsors.
Global sponsors and the caller's own hosted/joined events are marked
IsPriority=true and bypass Supercluster.
Radar¶
GetRadarData returns two Haversine-filtered lists, friends and
strangers, each a RadarUser with distance and live position. It reads
friend positions and presence from Redis via the shared cache. Radar is
the "who is around me right now" list behind the map.
Radius ceiling and read-time sharing check
The candidate query is not spatially filtered, so radius is capped at
50km (maxRadarRadiusMeters in handler.go) and anything larger is a
400, along with a lat/lng outside [-90,90] / [-180,180]. Every
position is also re-checked against the target's is_location_shared
before it is returned: the cached user:location:{id} entry carries its
own TTL, so key presence alone is not permission to reveal a position.
Search¶
Discovery exposes one unified search and three kind-scoped searches.
Unified intent (GET /discovery/search)¶
FindByIntent (service.go) takes a natural-language sentence
("wine tasting tonight", "sushi near me") and returns matching locations
and events plus how the query was interpreted, so the client can render
"showing X near you" hints (IntentPayload, IntentInterpretation).
- If
cityis set, forward-geocode it viaLocationService.Autocomplete(Photon) and use those coords as the anchor. This powers "bars in Toronto" from Ottawa with no client-side city picker; it falls back to the caller'slat/lngwhen Photon cannot resolve the string. - Run
taxonomy.ParseQueryagainst both theplaceandeventvocabularies and merge the tag sets. - Fan out concurrently to
LocationService.SearchandEventService.Search. Either side may be empty independently; no match on locations does not suppress events. Both sides only error out when both fail.
LocationService.Search is where the platform/llm semantic resolver
participates: it enriches Photon candidates through the search enricher.
Discovery itself holds no LLM code.
Kind-scoped search (Find tab)¶
The Find tab searches events and places separately near the saved pin.
FindHandler (find_handler.go) reads client-supplied lat/lng when
present and otherwise falls back to the persisted pin.
| Path | Returns | Shape |
|---|---|---|
/discovery/search/events |
{ events: FindEvent[] } |
Cover, when-label, distance, friends-going stack, tier/city/country_code |
/discovery/search/locations |
{ locations: FindLocation[] } |
Rating, open-state, distance, recent friends, tier/city/country_code |
/discovery/search/users |
{ users: [...] } |
Name/username ILIKE (min 2 chars), friendship status, optional mutuals |
Sparse-area widening and tiers (search_tiers.go). Event and place search
treat the requested radius (places default to 50 km) as the area. When fewer than 12
results land inside it (counted after the category, audience and place filters),
one widened query runs: 400 km for a keyword query, 150 km for a browse. Widened
results outside the pin's country (taken from the nearest result) are dropped. Every result carries tier, city (localized) and country_code:
tier |
Distance from the pin |
|---|---|
area |
Inside the radius |
nearby |
Up to 4x the radius, capped at 100 km |
city |
Beyond that |
Results are ordered area (ranked as usual), then nearby (same score, which already
includes proximity), then up to 3 city groups of 10, grouped by city and country
and ordered by each group's best-ranked result, so the existing friend and social
boosts decide which cities lead. A city-tier result with no city is dropped. Tiers
never interleave.
Event search only: when area, nearby and city results together still number fewer
than 12, up to 10 events from beyond 400 km (any country) are appended with
tier: "elsewhere", after every city group. They rank by friends going, then going
count, then soonest start. A typed query admits only strong matches (title
word-prefix or better, a named category, or a near-paraphrase); a browse admits all.
Place search never returns this tier. Without a pin every result
is area and nothing widens. The home feed calls event search without a radius, so
it does not widen.
Place filters. /discovery/search/locations takes optional filters applied
after enrichment and before the 60-result cap (a filtered search ranks a 200-candidate
pool): price_max (1-4, a known price level at most this), min_rating (0-5),
friends=true (a friend visited recently, the recent_friends source),
awards=true (a curated distinction in collections) and has_events=true (an
upcoming event here). Out-of-range values return 400. category accepts a place bucket id or
label (food) and expands to every category the place taxonomy files under it; a
leaf category matches itself, case-insensitively. The category list is pushed into the
recall query, so a browse filters before its pool limit. A place bucket the query
names ("drinks", "nightlife") also filters by the bucket's categories, not by row
tags. Multi-word taxonomy labels resolve
as one phrase in ParseQuery ("outdoor seating" is the outdoor-seating tag), so
tag queries find places and events by tag; tags also feed both embedding texts.
Personalization. A bounded tilt from the viewer's UserContext. It reorders
results inside a tier and never filters, changes counts or turns a non-match
into a match. The strongest personal pull stays below the gap between an exact
title or name and a weaker match (unit-tested bounds).
- Bucket affinity. Category affinities roll up to taxonomy buckets
(
UserContext.BucketAffinitieswithtaxonomy.BucketsOf): each bucket scores the mean of its member keys, so an RSVP to one Nightlife event lifts every Nightlife path. Events read the exactBucket/Subkey, else the bucket; places read the leaf, else the mean of its buckets. - Events also count an attended host (the viewer joined one of the host's
events before,
AttendedHostIDs) as +1 in the social term, and add a tap term (weight 0.05) from thetappedinteraction edge on the event or its host. - Places add 0.05 x the saturated
tappededge on the place, on top of the existing affinity, saved and dismissed adjustments. - Dismissed places (dismissals or a
dismissededge) and dismissed events (dismissededge) leave browse (no query) only; a typed search still finds them. saved=trueon/discovery/search/locationslists the viewer's own saves plus the places on their own stash and plan items, nearest first within 400 km, tiered as usual. Every place item carriessaved(the viewer's own save or stash entry). Only the viewer's state is read; another user's saves never appear.interests. Both search responses add a top-levelinterests: [{bucket, score}], the viewer's strongest buckets for that entity (canonical bucket ids, at most 5, only scores above the neutral 0.5), for ordering category sections. A cold-start viewer gets an empty list and the client falls back to count order.
Event filters and sort. /discovery/search/events takes optional
friends=true (a friend is going or hosting, from the viewer's own graph),
time_of_day (morning 05-12, afternoon 12-17, evening 17-22, late 22-05,
in the event's local time from its coordinates) and spots=true (no capacity
limit, or fewer going than max_capacity, the host included). They apply while
ranking, so before the sparse-area check and the 60-result cap. sort is
recommended (the ranking, default), soonest or nearest; place search takes
recommended, top_rated (rating weighted by its count), nearest, trending or prominence. A sort
orders results within each tier; tiers never interleave. Bad values return 400.
Must-see places. notable=true (filter, order with sort=prominence) on /discovery/search/locations ignores q
and returns the area's notable places in any category: rows with prominence of
at least 0.35, curated or city-highlight-promoted rows (unesco_seed,
wikidata_seed, promoted; a natural_seed feature qualifies only by prominence), award-listed rows and attraction-category rows
(SearchLocationsHighlights). They are ordered by prominence, then rating weighted
by its count, then distance. Radius, tiers and filters apply as usual; a sparse area
widens 400 km so it falls back to the nearest city's highlights. Every place item
carries prominence (0..1) and notable (prominence at least 0.35 or a curated
distinction).
Match confidence. A typed query (q set) on /discovery/search/locations and
/discovery/search/events marks each item match. strong: the name or title
matches, or the item carries what the query names. A bucket query ("food",
"nightlife", "drinks", or a bucket synonym such as "hike" for events and places) makes
every item in the bucket strong. A leaf query (a leaf category or plain tag such as
"ramen", "museum", "coffee", "night") makes only that leaf and tag hits strong, and
the rest of its bucket related (related_to names that bucket). With embeddings on,
a semantic similarity of at least 0.60 is also strong and at least 0.50 (events: the
window's match cut) related. A name hit and a category hit are equally strong and
keep the normal ranking order among themselves. Strong results come first and keep the
tier ordering; related ones follow, area tier only, at most 12, ordered by the same
sort (match.go). Only strong matches count toward filling the area, so related
items never block widening to nearby and city tiers. Anything else the recall pulled
in is dropped. The response adds truncated: true when the 60-result cap
(searchResultCap) dropped strong results. did_you_mean (a close spelling of a name or title in the pool,
similarity of at least 0.8) is added when nothing matched directly. Gibberish with no
strong, related or suggestion returns an empty list. The place search also returns
fallback: "eligible" when a typed name has no strong match and paid lookups
are on; the client then looks further on its own (Paid fallback). Browse is unchanged.
Top pick. A browse of events (empty q, default sort) with at least 6 results
marks at most one event top_pick: true with pick_reasons, a subset of
friends (2+ friends going or a friend host), interest (the event's bucket is among
the viewer's top interests), soon (starts within 7 days), nearby (tier area) and
spots (no capacity limit or open spots) (top_pick.go). An event needs 3 or more
reasons; the highest-ranked qualifier wins, and an event the viewer hosts never qualifies. Typed queries and small result sets never
get one.
Trending places. sort=trending on /discovery/search/locations ignores q and
lists places inside the radius ranked by recent Tomoda activity (trending.go,
TrendingLocations, one SQL query). Sources over the last 14 days: check-ins, public
moments, saves, stash and plan items, and location taps, saves and plans from the
activity stream. Each distinct user counts once per place per day, decayed with a
3-day half-life; friends of the viewer weigh 2x; the viewer's own activity is
excluded. A place needs at least 2 distinct users, and fewer than 3 such places in
the area returns an empty list so clients hide the shelf. Items carry
trending_score (0..1, omitted when 0). Only aggregates are exposed; who interacted
shows only through the existing recent_friends signal. Radius, place filters and
category apply as usual; nothing widens. The area's per-user, per-day activity for
its top 300 places is one query bounded to the area's places before aggregation
(TrendingActivity) and cached per geohash cell, radius and window for 2 minutes;
the viewer's exclusion, friend weighting and the distinct-user minimum are applied
per request (rankTrending).
Event ranking (event_rank.go) runs on the shared ranking spine
(internal/platform/ranking). ListEvents fetches a broad candidate window (up to
200 visible events near the pin, privacy-scoped by the event store) and scores each
with a normalized 0..1 blend:
| Signal | Weight | Meaning |
|---|---|---|
| Name | 0.55 |
Graded title match (spine name tiers) on the raw query and its free text |
| Category | 0.50 |
Taxonomy intent against the stored Bucket/Sub category: 1.0 for the named leaf or bucket, 0.6 for a leaf also filed under a named bucket or for the bucket the query points at semantically |
| Tag | 0.08 |
Fraction of parsed tags (or, failing that, free-text words) on the event, separators normalized (21_plus = 21-plus) |
| Proximity | 0.10 |
Gaussian on distance, sigma 10 km |
| Affinity | 0.12 |
Viewer's affinity for the event's category, falling back to its bucket's rolled-up score |
| Social | 0.14 |
Friends going, log-saturated; a close friend counts twice, a friend host adds a bonus and an attended host adds +1 |
| Time | 0.18 |
Soon events outrank far-off ones (10-day half-life) |
| Semantic | 0.45 |
Cosine similarity of query and event vectors, mapped from the 0.40..0.70 band onto 0..1 |
| Tap | 0.05 |
The viewer's tapped edge on the event or its host, log-saturated |
Intent works without embeddings: taxonomy buckets and subcategories carry
synonyms (backend/data/*_taxonomy.json), English search words that imply them
("club", "clubbing", "party at night", "cocktails", "bar" imply Nightlife; "ramen"
implies the place food bucket). ParseQuery returns them as Implied and keeps
the words in the free text, so event search scores implied buckets like a named
bucket and place search also browses the implied categories near the pin. A bucket
hit outweighs a title word or prefix hit, so for "night" nightlife events lead a
title like "Stargazing Night".
The query is parsed against the event vocabulary only (ParseQuery(q, event)), so a
place canonical sharing a label ("nightlife", "karaoke") does not shadow the event
bucket or subcategory. A bucket arrives as a tag-kind hit and matches events in that
bucket whatever their tags. A category hit outweighs a title word or substring hit,
so "nightlife" leads with nightlife events.
An event is returned when it matches by name, category, tag, or meaning. A meaning-only
match needs a similarity of at least 0.40 and within 0.05 of the window's best
(always at 0.52 or above), calibrated on the Qwen3 score scale. The query is
also compared with one vector per event bucket (its name plus subcategories); when it
sits clearly closest to one bucket (at least 0.43, 0.02 ahead of the runner-up),
events in that bucket get the 0.6 category credit. That credit lifts ranking but is
not a match on its own. Friend/participant counts are computed once over the window
and reused for the display fields. Nil-safe, so anonymous ranks on intent + proximity
only.
Event embeddings. Each event carries a Qwen3-Embedding-0.6B vector (events.embedding, full 1024 dims; similarity and the idx_events_embedding_hnsw index use the first 512) over its
title, category path, tags, venue name and the first 400 characters of its
description. The cron:event_embed_sweep job (every minute, 64 events in batches of
8) embeds live events whose embedded_at is null: new rows, rows the backfill has
not reached yet, and rows whose title, description, category, tags or venue changed
(the store clears embedded_at on those edits; the old vector keeps serving until it
is replaced). After a reseed (task db:test:setup, simulation) the same sweep
backfills the seeded events. Bucket vectors are computed in the background on first use,
memoized in process and through the same Redis query-vector memo.
Embeddings dependency and fallback. Embeddings are an additive boost; search
ranks on the lexical and taxonomy signals alone when they are off. A circuit
breaker in platform/embeddings opens for a minute after a failed or timed-out
call (a caller's own cancel does not count): while it is open every call returns
ErrUnavailable without touching the network, so a dead server costs search
nothing. It logs one WARN per trip and one INFO on recovery, and the embed sweep
ends its tick quietly (success to Asynq) instead of failing the task. Semantic scoring needs EMBEDDINGS_ENABLED
and a reachable TEI server (platform/embeddings). At query time the query is
embedded once (memoized in Redis as embed:qvec:{query}, shared with location
search) concurrently with the candidate fetch, then one exact-cosine query
(EventSimilarityByIDs) scores the window. The whole step is capped at 800 ms.
When embeddings are disabled, the server errors or times out, or an event has no
vector yet, those events rank on the lexical and taxonomy signals alone and the
client sees no error.
Local limitation
The embeddings compose service runs an amd64-only TEI image. On Apple
Silicon it runs under emulation at roughly 20 s per embed, so every call hits
the 2 s timeout and local search runs lexical-only (no event or location
vectors get written).
/discovery/search/locations delegates to location.Search (which is also
personalized); Discovery does not re-rank locations.
Home feed (feed.go, GET /discovery/feed) returns two sections the client
renders below a pinned brand header. A hero (greeting + map preview) sits on top
with the feed peeking below it; scrolling down snaps the feed to center
under a sticky, centered Moments/Events tab selector (content starts below the
tabs). Each item fills the height between the header and the bottom nav, one at a
time, swipe up/down for both: a moment shows exactly like the moment viewer,
an event shows as a cover card (its cover art, or a generative category cover
when none is set). Tapping the active tab jumps back to the hero. The moments pool
is retrieved from social sources — the viewer's own moments, close friends,
friends, bounded 2-hop friends-of-friends (public only), and moments a friend is
tagged in — deduped to the strongest source tier, scored on the spine
(social-proof, recency, popularity, affinity, proximity), capped by a per-author
diversity limit, then ordered unseen-first, each group newest-first. Every
moment carries a seen flag, a location_id (for the save-to-plan action), and a
per-viewer user_liked flag (an index-backed EXISTS on moment_likes in the
feed queries) so the heart renders correctly across sessions. The moment tray is
cursor-paginated: the first request ranks the full eligible set, freezes that
order (id + tier + seen) in Redis (feed:snap:{uid}, 15m TTL), and returns a
feedPageSize window plus a next_cursor; later requests (?cursor=) re-project
the next window from the frozen order, so pages stay stable even as the seen-set
advances mid-scroll. Events are bounded and returned on the first page only. The events section
reuses ListEvents with an empty query (browse-mode ranking), then drops events
the viewer hosts or has joined (discovery shows what's new; the viewer's own
events live in their events view). Search stays comprehensive. Each card carries a
"why" (e.g. "Jo posted" or "Your moment"). Anonymous/degraded reads are nil-safe.
FoF is capped + public-only; the feed includes the viewer's own moments (shared-album feel).
Seen-behavior. The feed leads with moments the viewer has not seen, so a
refresh surfaces fresh content instead of replaying; when the unseen run ends it
keeps going into already-seen moments chronologically (the client marks the "all
caught up" seam at the first seen card). Unseen cards are selected before the
cap, so a fresh moment is never crowded out. The seen-set is a Redis set owned
by discovery (feed:seen:{uid}, a JSON blob via SetCache, 14-day TTL, bounded
to 500 ids) — independent of the activity firehose and its sampling/retention. The
client POSTs /discovery/feed/seen with moment ids as each scrolls into view;
the read (seenMomentSet) partitions the feed. Anonymous or empty reads fall back
to plain newest-first.
Saving a search result to the capture Stash is a plan write:
POST /items/save-location (see Plans), not a Discovery route. The
location detail payload carries user_saved, computed via the SavedPlaceReader
port onto the stash store: true when the requester holds an active place-card for
the location, false for anonymous callers.
The location detail payload also carries collections, the curated-collection
prestige badges (Michelin stars plus award year, top-best rank), built from
CollectionsForLocations via distinctionFromMembership, the same shape the
search list uses. The award year comes from the membership's distinction.year,
which can differ per region from the collection's edition.
Search and browse place items and the detail payload also carry award, the one
strongest entry of collections for the card tag (omitted when none qualifies):
{source, list, label, rank, stars, bib_gourmand, green_star, year}. pickAward
(award.go) orders Michelin stars, then a ranked top-best list (best rank), then
Bib Gourmand, then UNESCO; notable overlays and unranked lists earn none. list
is the collection title (the place page line) and label the card text built from the
list's location_collections.short_title: "#12 Asia's Best Bars" for a ranked list, the
short title alone otherwise, falling back to the title. The seeder stamps short_title
from list metadata (topbest.List.short); the loader derives it from the list slug when a
seed file predates the field, and the search-discovery migration backfills lists already loaded.
Query parameters¶
All four endpoints (search/events, search/locations, browse/events, browse/places) are GET
with query params parsed by one typed struct, Query (query.go): ParseQuery
range-checks lat, lng, radius (1000 to 200000 m), price_max, min_rating,
time_of_day and the RFC3339 time bounds start_after, start_before and end_after
(events still running at that time); Validate(entity) returns 400 for a param that does not apply to
the entity (place filters on events and the reverse, top_rated/trending/prominence
on events, soonest on places); browse accepts only the area. Search params are
filters and a sort only: collections are browse sections, expressed in search as a
filter or sort (sort=trending, notable=true, saved=true). The same struct is the
JSON body a POST /discovery/search would take.
Browse (GET /discovery/browse/events, /discovery/browse/places)¶
Browse and typed search are one ranking pipeline. ListEvents and
ListLocations are the stages eventPool/placePool (recall, widening, filters,
scoring with the shared UserContext signals, tiering) followed by a cap and
enrichment. Browse calls the same pool functions, then partitions the result into
sections, so ranking, personalization and tiers cannot drift between the two. A
section's see_all.params are the exact search params that reproduce it.
{ "layout": "shelves|list|sparse",
"sections": [{ "id": "", "title_key": "", "title_args": {}, "kind": "carousel|grid|hero",
"card_size": "regular|large", "tier": "area|nearby|city|elsewhere",
"items": [], "see_all": { "params": {} } }],
"interests": [{ "bucket": "", "score": 0 }] }
The server owns which sections exist, their order and sizes: a carousel needs 3
items and a grid 4 (a short leftover section renders as a carousel). layout is
sparse below 6 area results, shelves at 24 or more area results in 2 or more
area sections, else list. Sections of tier: area partition the in-radius
results; nearby and city (one section per city) follow, ordered as in search.
| Events (in order) | id |
Rule | see_all |
|---|---|---|---|
| Top pick hero | top_pick |
the event the top-pick rule selects, one item, never one the viewer hosts; empty title_key (no header) |
none |
| Friends | friends |
friend host, or 2 or more friends going; at most 8 | friends=true |
| Tonight | tonight |
starts before 04:00 next morning in its own timezone, not ended; at most 12 | end_after, start_before |
| This weekend | this_weekend |
Friday 17:00 to Sunday 23:59 in its own timezone, not ended; at most 12 | start_after, start_before, end_after |
| Coming up | coming_up |
the rest, in rank order | none |
| Tiers | nearby, city:<name> |
search's tier layout | none |
| On Tomoda | elsewhere |
under 4 events in the pin-free pool: up to 6 events from anywhere, through the same ranking | none |
Each event lands in the first section it qualifies for. Going counts, the viewer's participation and friend avatars are read once over the events shown.
| Places (in order) | id |
Rule | see_all |
|---|---|---|---|
| Trending | trending |
the sort=trending pool, 3 or more |
sort=trending |
| Saved | saved |
the viewer's own saves in the area, 3 or more | saved=true |
| Must-see | must_see |
the notable=true pool, only when the area's city differs from the viewer's home city (or is over 50 km from the home pin) |
notable=true, sort=prominence |
| Top rated | top_rated |
rating 4 or more, ranked by rating weighted by count | min_rating=4, sort=top_rated |
| Friends | friends |
a friend visited recently | friends=true |
| Awards | awards |
a curated distinction, Michelin first then top-best | awards=true |
| Categories | category:<bucket> |
up to 5 buckets of 3 or more, ordered by the viewer's interests then size | category=<bucket> |
| More places | more_places |
area places no section rendered | none |
| Tiers | nearby, city:<name> |
search's tier layout | none |
A place appears in at most two sections. title_keys are search.* locale keys;
title_args carry city, category or km.
Pool cache. The non-personal place recall (the candidates and base scores from
location.Search, and the highlights pool) is cached per precision-6 geohash cell,
radius, language and limit for 3 minutes (browse:pool:*, see
Redis keys), and recalled around the cell center
so every viewer in the cell sees the same pool. The viewer overlay (affinity,
saves, dismissals, taps, friend visits, saved flags, friend avatars) is applied per
request through LocationService.Personalize, the same step location.Search
runs, and is never cached in the shared pool. Event recall is scoped to what the
viewer may see (friends-only events), so it is not shared.
Saved pin (GET/PUT /discovery/pin)¶
The Find tab's area selector. FindLocationState carries the pill label,
anchor lat/lng, radius (km), and a recents list. The frontend seeds it
from device location, updates it from the location picker, and every
search request carries the current area.
Personalization and category affinity¶
Every personalized ranking (location search, event search, home feed) reads a
per-viewer UserContext from internal/services/personalization: category
affinity scores (0..1, 0.5 neutral), saved and dismissed location ids, and
rolled-up interaction edges. It is cache-first (Redis blob, short TTL) and
nil-safe, so an anonymous or degraded read ranks on intent and proximity alone.
Category affinity is the taste profile the recommender leans on. Scores live
in user_affinity(user_id, category, score), owned by the maps domain. Two
things move them:
- Signals (immediacy). An action folds an intent-weighted delta into the
acted-on category through
maps.Service.RecordAction. The weights live in one table,personalization/action_weights.go(delta = weight * 0.05):
| Action | Weight |
|---|---|
| Impression | 0 (never counts) |
| Detail open | 0.1 |
| Tap, category search or filter | 0.2 |
| Save | 1.0 |
| RSVP maybe | 0.5 |
| Join / going | 1.5 |
| Check-in, moment at the place | 2.0 |
| Hosting | 2.0 |
| Dismiss | -0.8 (that item's bucket) |
The lift fades toward the 0.5 neutral baseline with a 30-day half-life (by
user_affinity.updated_at), applied on every read and again before a delta is added, and the
score is clamped to 0..1, so the interests threshold (above 0.5) stays
meaningful. An item moves a user's score at most once per action per day
(affinity:cap:{uid}:{action}:{item}, 24h SETNX, released if the write
fails), so repeated taps cannot dominate. Every write busts the cached UserContext, so the next search's
interests reflects it. Taps and detail opens arrive in activity.LogEvents
(verbs tap, select, view on an event or location) and resolve the
target's category server-side in one batch per log call (events only when
visible to the viewer), with one write per category and one cache bust. Search signals come from ListEvents and
ListLocations. Scores are stored per category key; the bucket roll-up
happens at read time (UserContext.BucketAffinities with taxonomy.BucketsOf).
Saves and dismissals write inside the save transaction (maps/service.go,
affinityTx); unsave and leave drop a fixed 0.03.
- Reconcile (correctness). A lazy reconcile fills gaps. maps.ReconcileAffinity
drops scores with no signal in the last ~60 days, then recomputes categories
from that window's actions without overwriting a score a recent signal already
moved; each action lifts its category 0.05 above the 0.5 neutral baseline
(saturating at 1.0). It is triggered from
personalization.Build on a cache miss (roughly the context TTL cadence per
user), runs fire-and-forget on a detached context, and self-throttles on a
Redis watermark (affinity:reconciled:{uid}, 7-day TTL: key present means
fresh). A dormant window (no recent actions) keeps the existing profile and
just re-stamps the watermark, so a returning user is never wiped.
Adding a taste signal (the extensible seam)¶
maps.Service.BumpCategoryAffinity(userID, category, up) is the single write
path, and it busts the viewer's cached UserContext. A domain that emits a taste
signal consumes it as a one-method inbound port, so signals grow without coupling
domains to the maps package. Three steps:
- Declare an
AffinityBumperport in the domain'sdeps.go(one method, matchingBumpCategoryAffinity). Seemoment/deps.gofor the reference. - Bind it in
wiring/providers.go:wire.Bind(new(<domain>.AffinityBumper), new(*maps.Service)). - Call it on the action (
up=true) and its reversal (up=false) with the resolved category. A nil bumper is a no-op, so tests and seeders need not wire it.
The taste signals wired today, all through this seam:
| Signal | Direction | Category from | Site |
|---|---|---|---|
| Save / dismiss a location | up / down | location | maps/service.go (affinityTx) |
| Like / un-like a moment | up / down | moment | moment/service.go (ToggleLike) |
| Join / leave an event | up / down | event | event/event_service.go (JoinEvent, LeaveEvent) |
| Add a place to a plan | up | location | plan/item_service.go (ensurePlanLocation, SaveLocation) |
| Check in at a location | up | location | presence/checkin_service.go (CreateCheckin) |
| Tap or open an event or place | up | target row | activity/service.go (signalTaps) |
| Host an event | up | event | event/event_service.go (CreateEvent) |
| Category search or filter | up | query / filter | discovery/search_service.go (recordSearchInterest) |
Check-in and plan-place are up-only (their removals are weak, logistics-driven signals); the lazy reconcile is the drift control for those.
Taxonomy vocabulary¶
TaxonomyHandler (taxonomy_handler.go) wraps the shared
platform/taxonomy service and serves its localized vocabulary under
/discovery/taxonomy. The frontend fetches it once per locale on boot and
renders every category badge, tag pill, picker row, and search filter from
that snapshot.
| Path | Description |
|---|---|
/discovery/taxonomy |
Full vocabulary localized to lang (falls back to Accept-Language, then en). taxonomy.LocalizedTaxonomyPayload. |
/discovery/taxonomy/resolve |
Resolve one free-text q to { query, entity, canonical, kind } where kind is category, tag, or "". entity narrows to place or event. |
The vocabulary itself is a shared platform concern, loaded once at boot
from backend/data/*.json and consumed by location, event, and discovery
alike (there is no categories table). Its concept model:
- Bucket categories: top-level groupings (
food,culture,nightlife). Canonicals are lowercase. - Subcategories: leaves under a bucket (
food → cafe / restaurant). Search widens a bucket into the subcategory IN-set the place repo stores. - Facet tags: orthogonal modifiers (
wifi,outdoor-seating,vegan). Each declaresapplies_to_categories("*"means anywhere).
The rich-detail flag on a bucket (RichDetailTags()) is the only knob
that escalates a Photon match into paid Google enrichment; see
Locations → Provider policy. The optional
dedup_radius_m per category drives the location dedup radius; see
Locations → Dedup story.
| Data file | Owns |
|---|---|
backend/data/place_taxonomy.json |
Place buckets + subcategories + facet tags; rich_detail, dedup_radius_m, default_tags |
backend/data/event_taxonomy.json |
Event buckets + subcategories + tag families |
backend/data/curio_categories.json |
Curio categories with 28-locale translations |
Longest-match tokenization
ParseQuery scans CJK / scriptio-continua input character by
character, picking the longest known label at each position, and
tokenizes space-separated languages on whitespace. That is why
"ラーメン居酒屋" splits into two matches rather than one blob.
Public profile¶
GetUserProfile returns the privacy-aware UserProfilePayload: identity,
friendship_status, recent moments, mutual friends (count and, for authed
callers, the list), and upcoming + past events. Auth is optional so share
links resolve unauthenticated; an authed caller gets viewer-relative
fields. friends_only moments and events appear only when the requester
is an accepted friend.
The card is a passport surface, so it runs the target's
passport_visibility ladder through the user domain's GetForViewer
before it is assembled (ProfileVisibilityReader in service.go).
Anonymous callers are measured as a viewer that can never be a friend, and
a private passport answers 404 rather than confirming the account exists.
See User for the ladder itself.
Journal (GET /discovery/profiles/:id/journal)¶
The passport's unified "what I've done" record, auto-grouped server-side.
ListJournal reads the target's travel log newest-first (the
geography-bearing spine, so every entry carries a country, city, and
location) and attaches a payload per entry: a visible moment makes it a
moment entry; a matched event_id (LEFT JOINed to events) makes it an
event entry carrying an EventBrief ("attended {event}"); a bare check-in
stays a visit entry. Plans and future events never appear: the travel log
records only past, proven visits. The same passport_visibility ladder gates
the page as the profile card; a viewer the passport is closed to gets an empty
page.
segmentJournal (a pure function in service.go) groups the entries. A
logical day buckets by local_time (fallback visited_at) with a
pre-dawn cutoff of logicalDayCutoffHour (4): an entry before 04:00 local
folds into the previous logical day, so a 23:00 dinner and a 01:00 club group
together.
| Kind | Rule |
|---|---|
trip |
A contiguous run of entries in a non-home country, bounded by a return to the home country, a country switch, or a time gap > tripGapDays (2). Title is the country; subtitle is the distinct cities. |
day |
>= dayOutMinItems (2) entries the same logical day in one city, even at home, that aren't already inside a trip. |
single |
An isolated entry. |
Home base is the profile's HomeCountry/HomeCity, falling back to the
modal country across the page; activity in the home country is never a trip.
Each JournalSegment carries stops: a JournalStop is the entries at one
location_id within one logical day, with its own logical_date, start/end,
moment/event counts, up to four moment thumb_urls, and the EventBrief when
the stop is an attended event. A trip carries all its stops (the client groups
them by logical_date); a day/single carries its stop(s). The segment rolls up
a date range, per-type counts (moment_count / event_count / visit_count),
and a cover (the first moment image in the run). Pagination is keyset by
(visited_at, travel_log_id); next_cursor is the oldest entry's cursor. A
trip spanning the page boundary may split at the edge, which the client merges
by the stable segment key.
Atlas region drill (GET /discovery/profiles/:id/atlas/:country/regions)¶
GetCountryRegions returns the viewer's visited admin-1 regions within one
country (resolved via user_travel_logs.region_id joined to regions), each
carrying region_id, name, iso_3166_2, depth, visit_count, and a
boundary GeoJSON polygon (ST_AsGeoJSON over a server-side
ST_SimplifyPreserveTopology). Only rows with a non-null boundary are returned,
and the query is bounded to one country so the payload never carries all regions
globally. Gated by the same passport_visibility ladder; a closed passport, or
a country with no boundary-bearing visited regions, returns an empty list.
Key types¶
Response shapes live in backend/internal/services/discovery/types.go.
Small cross-cutting briefs (UserBrief, EventBrief, MomentHighlight)
are duplicated per domain by design; the Discovery copies are its own.
| Type | Used by |
|---|---|
DiscoveryPayload / MapMarker / ClusterCounts |
/discovery/map |
RadarPayload / RadarUser |
/discovery/radar |
LocationDetailPayload / OpeningHours |
/discovery/locations/:id |
IntentPayload / IntentInterpretation / IntentLocation / IntentEvent |
/discovery/search |
FindEvent / FindLocation / FindLocationState |
Find tab search + pin (find_service.go) |
UserProfilePayload |
/discovery/profiles/:id |
JournalPage / JournalSegment / JournalStop / TimelineEntry / EventBrief / TimelineVisitBrief |
/discovery/profiles/:id/journal |
AtlasIndex / CountryPage / CountryRegions / AtlasRegionGeo |
/discovery/profiles/:id/atlas… |
Invariants and gotchas¶
Spatial reads are raw SQL
PostGIS geometries are scanned back as floats through
ST_X(coordinates) AS lng, ST_Y(coordinates) AS lat. Do not map the
geometry column directly, pgx cannot decode the geometry binary form
and silently drops rows.
Map panning returns 499, not 500
GetDiscoveryData fires on every viewport change and the client
aborts the in-flight request. That surfaces as context.Canceled;
the handler responds 499 (client closed request) so normal panning
does not show as server errors in access logs.
Opening hours are rendered from periods on read
models.Location.OpeningHours stores the structured periods only
({"periods":[...]}); the English weekday_text is intentionally not
persisted. GetLocationDetail renders the OpeningHours.weekday_text
lines Monday-first from those periods via
location.FormatWeekdayText, the same helper the search and maps
surfaces use, so all three display identical hours.
Where to look¶
backend/internal/services/discovery/service.go: map, radar, location detail, profile,FindByIntentbackend/internal/services/discovery/find_service.go: Find tab search + saved pinbackend/internal/services/discovery/handler.go,find_handler.go,taxonomy_handler.go: HTTP surfacebackend/internal/services/discovery/routes.go: route registrationbackend/internal/services/discovery/types.go: response payloadsbackend/internal/platform/taxonomy/: the shared vocabulary service + data loadingbackend/internal/services/personalization/: theUserContextbuilder (affinity, saves, dismissals, edges)backend/internal/services/maps/service.go:BumpCategoryAffinity(the taste-signal write path) +affinityTx- Locations · Maps · Semantic Resolver · User