Open History to see the last commit
1# Hacker Realtime — implementation plan and status
2
3Status: implementation built and deployed; launch acceptance remains open. Prepared
42026-10-12. See [measured validation](docs/validation.md) for completed checks
5and outstanding launch acceptance work.
6
7## Goal
8
9Match the normal Hacker News interface, adding a few discreet controls for
10live updates. Stories, scores, comment counts, and feed positions update
11through Neon Realtime while the page remains open. Commenting and submissions
12take place on the real Hacker News site. The demo should be easy to run locally
13and suitable for sharing at launch.
14
15## Confirmed findings
16
17- HN's official public API needs no API key and describes its data as near real
18 time. Firebase supports live subscriptions to feed lists and individual items.
19- A read-only 45-second SSE probe received subsequent events from `topstories`,
20 `updates`, and an individual story. That story's score changed from 230 to 231.
21- `topstories` and `newstories` return up to 500 ordered IDs. Item records provide
22 titles, authors, URLs, scores, `descendants` comment counts, and `kids` IDs.
23- `/updates` supplies changed item and profile IDs. It is not documented as a
24 durable log with a replay cursor; recovery must refresh current state.
25- The local Next.js example combines SSR, Drizzle, sealed queries, and React's
26 `useLiveQuery`, including renewal after the initial capability expires.
27- Neon Realtime supports deterministic ordered queries, limits, and joins. Keep
28 age formatting in the browser rather than using `now()` in a live query.
29- Functions have a 15-minute time-to-first-byte limit and a 15-minute
30 `waitUntil` cap. Active response streams can last longer while bytes flow.
31 Outbound HN subscriptions alone do not establish an active response stream.
32
33Sources: the [HN API](https://github.com/HackerNews/API),
34[Firebase REST reference](https://firebase.google.com/docs/reference/rest/database#section-streaming),
35[Realtime preview docs](https://neon-next-git-thruflo-realtime-3-integration-neondatabase.vercel.app/docs/realtime/),
36and [Function runtime limits](https://neon.com/docs/compute/functions/reference/runtime-limits).
37
38## Demo scope
39
40### First version
41
42- Match the standard HN page: orange header and square RT logo, beige background,
43 Verdana typography, compact numbered rows, grey metadata, top/new/submit navigation,
44 and the usual More link. Check the current site at desktop and mobile sizes
45 before implementing the layout. Keep Neon Realtime attribution in the footer.
46- Top and new feeds, 30 rows per page. Start by tracking the first 150 items of
47 each feed; their union bounds upstream subscriptions and database work.
48- Use the source feed order for ranking. Support jobs and missing optional
49 story fields without broken rows.
50- Update scores and comment counts in place; use subtle, brief highlights for
51 changed values and new stories. Animate rank changes with reduced-motion support.
52- Place live/pause, a toggle for highlighting changes, and a compact
53 connection/freshness indicator at the right of the orange header; wrap on mobile.
54 Match the surrounding HN type size and spacing.
55- Pause freezes the displayed list while the live subscription continues.
56 Resuming shows the latest state without replaying every animation.
57- Show connection state and source freshness separately so an active Realtime
58 connection does not hide a stalled ingester.
59- Open story comment counts in local live nested discussions. Reply/comment,
60 profile, vote and Submit actions stay on real HN. Remove login from the header.
61- Fetch uncached first comments in the server route loader and navigation preparation;
62 seed the shared cache before subscribing, then render remaining comments progressively.
63- Watch every open discussion on the shared Firebase connection, up to 500 comments
64 per thread. Use independent viewer leases, release on departure, and expire abandoned
65 watches after 30 seconds. Show loading/stale/truncated states and original links.
66- Pulse only changed numbers and edited comment text. Expand arriving story/comment
67 rows, animate movement with stable IDs, and suppress motion on resume or when
68 reduced motion is requested. Allow comment branches to collapse.
69
70### Navigation and interaction destinations
71
72Preserve standard labels and ordinary link behavior, including opening a link
73in another tab. The live comment count remains the discussion link label.
74
75| Element | Destination |
76| ------------------------------- | ------------------------------------------------------ |
77| RT logo / Hacker Realtime title | This demo's top feed. |
78| Top / New | This demo's top / new feed. |
79| Story title | Original article URL; original HN item for text posts. |
80| Comments | Local live `/item?id={id}` thread. |
81| Story / comment age | Original HN item. |
82| Comment / reply | Original HN item / reply page. |
83| Submit | `https://news.ycombinator.com/submit`. |
84| Author | Original HN profile. |
85| Vote arrow | Original HN item, where HN handles voting. |
86
87URL-encode IDs, usernames, and any query parameters when constructing links.
88
89### Follow-up work
90
91Add locally mirrored Ask/Show/Jobs feeds and optional Algolia search. Keep
92reply and submission links pointing to the real HN site.
93
94## Application architecture
95
96Use Next.js, React, TypeScript, and Drizzle, adapting the local `realtime/nextjs`
97example. The application server reads initial rows from Postgres and seals
98fixed, parameterized feed queries. The browser uses a shared Realtime client,
99`RealtimeProvider`, and `useLiveQuery` with `initialData` and `refreshQuery`.
100
101Every feed result includes `item_id` and source `rank`. Use
102`ORDER BY rank ASC, item_id ASC` with the page limit/offset to select membership
103on the server. Sort a copy of the returned rows by the same keys before
104rendering SSR data and every live snapshot, including updates, resets,
105reconnects, and resume from pause. The current SDK materializes rows in a Map;
106its array order does not reposition an existing row when its rank changes.
107Apply each complete batch before sorting and use `item_id` as the React key.
108
109The browser's story data comes from Neon. A separate Neon Function mirrors HN
110into the same branch's database. Host the Next.js application on a platform
111that supports its Node server, with Vercel as the initial deployment choice.
112
113Use a prebuilt Vercel deployment for the initial demo. A clean checkout must
114fetch the pinned Neon sources and generate `.sdk/` packages before application
115dependency installation, then build and upload the complete application
116artifact. [Prerelease build and deployment](docs/prerelease-build.md) specifies
117the pipeline, package integrity checks, and deployment environment handling.
118
119Use bounded, validated feed and page parameters in the sealing endpoint. The
120Realtime secret remains server-only. The ingester accepts verified Function
121Trigger deliveries, using the SDK's trigger parser; arbitrary public requests
122must not start ingestion.
123
124## Database outline
125
126| Table | Purpose |
127| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
128| `hn_items` | HN ID as primary key; type, title, URL, author, creation time, score, descendants, deletion/dead flags, and relevant source fields. |
129| `hn_feed_entries` | Composite key `(feed, item_id)` and source rank; indexed for feed pagination and joined to `hn_items`. |
130| `ingest_leases` | Separate active/standby slots; owner, expiry, heartbeat, planned session end, readiness, and an active fencing token to coordinate invocations across isolates. |
131| `ingest_status` | Last healthy connection check, successful reconciliation, source event, committed write, latest failure, and handoff/recovery timings for freshness reporting. |
132
133Use primary keys and `REPLICA IDENTITY FULL` on subscribed tables. Publish feed
134membership and rank changes in a transaction. Fetch missing items before
135publishing their feed entries so the UI does not briefly show incomplete rows.
136Update source columns only when they differ, avoiding unnecessary writes and
137Realtime batches. Preserve IDs as React keys so changed ranks retain row identity.
138
139The discussion tables are `hn_threads` (cache load ownership, health and truncation),
140`hn_thread_views` (per-page viewer leases and release tombstones) and `hn_comments`
141(composite story/item key, parent, deterministic path/depth, text and deletion/dead
142state). Self-post text is stored on `hn_items.body`. Cold page loads claim a short
143per-thread lease without holding a connection over HN requests, then seed initial
144comments only if the worker has not populated the cache. A row lock serializes
145seeding with worker publication. Incomplete snapshots only add missing rows;
146complete worker snapshots conditionally update and delete in the globally fenced
147transaction. Thread queries order by path then item ID, including both composite
148key columns. Feed readiness permits handoff independently of cold discussions;
149cached rows survive the successor's partial tree until reconciliation completes.
150
151## Ingestion design
152
153Use a scheduled Function Trigger every minute. With no active owner, an
154invocation acquires the active Postgres lease and begins reconciliation. Most
155calls return immediately while that owner is healthy. During the final two
156minutes of its planned session, one call reserves the standby slot, connects
157to HN, and prepares current feed/item snapshots. Further calls return while
158that standby slot is occupied. Only the active owner publishes feed writes.
159Keep all ownership decisions in Postgres because Functions can run multiple
160isolates.
161
162The implemented active session is two minutes, with a 90-second preparation
163window and a four-minute absolute request budget. Native scheduled deliveries
164completed after 120–181 seconds. The trigger caller's full fifteen-minute
165timeout remains unverified; the demo uses the shorter measured configuration.
166Both roles must finish their requests within the caller
167limit. Record an absolute request deadline on arrival, including standby
168preparation time and a cleanup margin. Promotion never resets that deadline;
169the new active tenure is capped by the invocation's remaining budget. If the
170caller limit is shorter, choose a shorter active session and preparation window
171that still allow overlapping scheduled invocations to meet the handoff budget.
172If no measured configuration meets the budgets below, the ingestion gate
173fails: record the limitation and propose a supported alternative before
174declaring the live demo ready. UI work can continue independently.
175
176Lease settings: renew every 5 seconds with a 20-second expiry. Verify
177the owner, unexpired lease, and fencing token under a row lock in every feed
178write transaction. A failed renewal stops publication and aborts pending work.
179Treat these settings as values to verify in the lifecycle probe.
180
181Each active session:
182
1831. Acquires its role's lease and refreshes the bounded top/new feed snapshots.
1842. Subscribes to feed lists and tracked item nodes. Prefer Firebase's SDK so
185 many item listeners share a connection; SSE remains a fallback.
1863. Coalesces events into small write batches, preserving processing order.
187 Applies inserts, source changes, removal flags, and feed changes to Postgres.
1884. Renews ownership periodically. A standby stays read-only for feed data and
189 marks itself ready once the current tracked set has initial values and its
190 source connection is healthy. Every feed write verifies active ownership and
191 fencing, so an expired worker cannot publish after takeover.
1925. Reconnects with backoff and refreshes authoritative state after reconnects.
1936. Near its session deadline, flushes accepted batches and atomically transfers
194 active ownership to a ready standby, incrementing the fencing token. The
195 promoted invocation detects ownership promptly, reconciles current source
196 values, and starts writing. Discard superseded queued snapshots rather than
197 replaying an old owner's backlog. The retiring invocation removes listeners
198 and completes its response. Handle `SIGINT` with best-effort cleanup within
199 Neon's five-second shutdown window.
200
201Poll ownership every 250 ms while a standby is ready for transfer. Keep the
202number of source sessions bounded to one active plus one standby. If the
203active owner dies, a prepared standby can take over after lease expiry;
204otherwise a subsequent scheduled call performs cold recovery. If no standby
205is ready at the request deadline, stop cleanly, report degraded ingestion, and
206recover on a later call; that run fails the planned-handoff acceptance check.
207
208This mirrors current HN state rather than preserving every intermediate score
209change. Reconcile at least every 60 seconds and after reconnects or ownership
210changes. Persist progress and health, not a fabricated HN replay cursor. A
211quiet but connected source is healthy: freshness must use successful connection
212checks/reconciliation rather than the time of the last changed story alone.
213
214### Measured demo budgets
215
216These are implementation acceptance targets, not platform guarantees. Measure
217with correlated events/transaction IDs and synchronized clocks; include feed
218membership and rank changes as well as score/count updates.
219
220| Measurement | Acceptance target |
221| -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
222| HN event received by the active ingester to database commit | p95 <= 2 seconds; p99 <= 5 seconds. |
223| Committed change to sorted rows applied in an unpaused browser | p95 <= 2 seconds; p99 <= 5 seconds. |
224| Planned ownership handoff, from old owner stopping publication to new owner ready to publish | <= 5 seconds for every observed handoff. |
225| Forced active-worker termination to reconciled ingestion restored | <= 120 seconds. |
226| Source health reporting | Mark degraded within 30 seconds of failed checks or loss of ownership; show an explicit reconnect immediately when detected. |
227
228HN's delay before publishing an API event is outside these measurements. Record
229the source-received, committed, and browser-applied times separately. Validate
230at least three planned handoffs, cold and warm forced recovery, and 100 observed
231source changes across two tabs. Use isolated test records when controlled
232events are needed; do not fabricate scores in the mirrored HN data. A missed
233budget blocks launch until corrected or explicitly revised with the user.
234
235## Delivery phases
236
237### 1. Build the UI and prove staging in parallel
238
239Begin the UI track immediately; it does not depend on a provisioned database
240or a successful scheduled-function probe.
241
242- **UI track:** scaffold Next.js with public framework dependencies and a
243 representative local story fixture. Match the current HN desktop/mobile
244 layout, external interaction links, pagination, and compact controls. Keep
245 fixture mode explicit and development-only. Exercise rank swaps and inserted
246 rows against the same sorting function planned for live snapshots.
247- **Toolchain track:** resolve the SDK/CLI refs, pin exact commits, and implement
248 the bootstrap/packing pipeline before adding local SDK dependencies. Verify
249 it can install and build from a clean checkout using the lockfile, with no
250 pre-existing `.sdk/` packages or local Neon checkout.
251- **Staging track:** resolve the organization and dedicated demo project;
252 confirm Functions, scheduled triggers, and Realtime are available together.
253 Provision PG18 in `aws-us-east-2`, enable logical replication and Realtime,
254 and allow local origins; follow [staging notes](docs/neon-staging.md).
255- Deploy a minimal lifecycle probe with the lease schema and source
256 subscriptions. Measure the trigger caller's timeout, outbound streaming,
257 standby readiness, fencing, scheduled overlap, planned takeover, and forced
258 termination recovery. Keep reusable schema/probe code for later phases.
259
260Exit: the HN UI runs independently; prerelease packages reproduce from a clean
261checkout; and the staging probe has demonstrated a supported session duration,
262three handoffs within 5 seconds, and recovery within 120 seconds. If the staging
263gate fails, continue UI/toolchain work while recording and resolving the
264ingestion limitation. Do not rely on an untracked background promise after
265returning the Function response.
266
267### 2. Connect the app, database, and live queries
268
269- Extend the Next.js/TypeScript scaffold, Drizzle schema, repeatable schema
270 setup, and local package-build scripts from phase 1.
271 Record prerequisite Node and package-manager versions and commit the
272 dependency lockfile.
273- Seed a bounded real HN snapshot and render the top/new pages from Postgres
274 using the standard HN layout and canonical external interaction links.
275- Add server-side sealing and the browser Realtime provider, including renewal
276 and explicit sorting of projected ranks after every snapshot.
277
278Exit: the HN layout renders initial rows and committed database changes reach
279two open browser tabs through Neon Realtime.
280
281### 3. Implement shared ingestion
282
283- Add source subscriptions, tracked-item reconciliation, batched conditional
284 upserts, transactional feed updates, lease fencing, and the warm-standby
285 handoff proven in phase 1.
286- Add freshness records and structured logs for starts, source events, writes,
287 retries, lost leases, and shutdowns. Keep credentials out of logs.
288- Handle null, deleted, dead, and incomplete items, source reconnects, duplicate
289 deliveries, and clean session termination.
290
291Exit: real HN changes appear without refreshing, overlapping calls have one
292effective writer, planned handoffs meet the 5-second budget, and forced
293recovery meets the 120-second budget. Measure the normal ingestion/browser
294latency targets under the bounded two-feed workload.
295
296### 4. Polish, verify, and deploy
297
298- Add the compact live/pause and highlighting controls, subtle row transitions,
299 mobile layout, keyboard access, reduced motion, and clear stale/error states.
300- Compare the demo with the current HN layout at desktop and mobile sizes,
301 checking header, fonts, colors, row density, spacing, and navigation.
302- Decode titles into escaped text and validate outbound URL schemes.
303- Run type checking and a production build. Exercise the meaningful ingestion
304 and browser checks below; add focused automated coverage for lease fencing,
305 reconciliation, and feed ordering where failures would corrupt visible data.
306- From a clean checkout, generate pinned SDK packages before dependency
307 installation and run the prebuilt Vercel deployment pipeline. Verify the
308 server has its runtime dependencies, the correct server-only environment,
309 and the browser-visible URL baked into the build.
310- Allow the deployed origin and verify the browser connects directly to the
311 managed Realtime endpoint. Use the same artifact pipeline for subsequent
312 builds while packages remain unpublished.
313- Document local run, staging setup, package builds, deployment, and how to
314 disable ingestion. Ensure preview branches do not inherit an active ingestion
315 schedule unintentionally.
316
317Exit: the deployed demo stays current across a full ingestion handoff and
318Realtime capability renewal, meets the measured budgets across the required
319samples, and has a reproducible clean-checkout build/deployment documented.
320
321## Acceptance checks
322
323- Real score/count changes and source rank changes reach two open tabs.
324- Changing a row's rank reorders it correctly without changing its React key.
325 Rank swaps, inserted rows, page-boundary changes, resets, reconnects, and
326 resume from pause all use the explicit `(rank, item_id)` ordering.
327- SSR rows appear immediately; the first live snapshot reconciles intervening
328 changes. Subscriptions remain live beyond their original sealed-query expiry.
329- A new feed item is complete on arrival; removed items disappear atomically
330 with the appropriate feed update.
331- Concurrent trigger calls cannot write under stale ownership. Restarting an
332 ingester refreshes current state without duplicated items or corrupted ranks.
333- Three planned handoffs and both cold/warm recovery scenarios meet the stated
334 budgets; normal event-to-commit and commit-to-browser timings meet the p95/p99
335 targets across at least 100 observed source changes.
336- An upstream interruption marks source data stale; a Realtime disconnect
337 preserves the last rows and recovers to an authoritative snapshot.
338- Pause/resume, pagination, mobile use, and reduced motion remain usable.
339- The page retains the standard HN appearance, with extra controls confined to
340 the orange header and attribution in the footer.
341- Comment counts open local live nested threads. Comment/reply and Submit
342 lead to the original HN discussion and submission form; article, profile
343 and vote links have the specified destinations.
344- No database credentials or Realtime sealing secret enter browser assets or Git.
345- A fresh checkout with empty `.sdk/`, `.local/`, and `node_modules/` can generate
346 identical pinned package artifacts, install with the frozen lockfile, build,
347 and deploy the prebuilt application without the developer's local checkout.
348
349## Implementation decisions
350
351- Sam's staging organization owns the dedicated `square-paper-24289554` project.
352 Functions, schedules, Realtime and PG18 work together on its main branch.
353- Neon commit `3c08c9b45a919515a7b79977fa6267f828ce52d5` includes the merged CLI
354 Realtime support. `neon-toolchain.lock.json` pins its build and artifact hashes.
355- Two-minute active sessions, 90-second preparation and a four-minute request
356 budget are deployed. Publication continues while a delayed successor is
357 awaited, up to that same absolute deadline. Fifteen-minute scheduled requests
358 remain unverified.
359- Vercel hosts [the demo](https://hackernews-realtime.vercel.app/); its stable
360 origin and configured preview origins are allowed by Realtime.
361- Build and deployment passed. The exact completed measurements and remaining
362 launch gates are recorded in [validation](docs/validation.md).