Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

README.md

176 lines7.2 KB

1# Hacker Realtime
2​
3A familiar Hacker News interface where stories, scores, rankings and comment
4threads update live. New stories expand into the list, stories animate as their
5rank changes, and updated scores and comment counts light up individually. A
6moving timeline lets you inspect changes across the demo, including items
7outside your current view.
8​
9The demo is built with **Neon Realtime**, which lets applications subscribe to
10live Postgres query results. When the underlying data changes, Neon Realtime
11sends updates to the browser so the interface stays in sync automatically.
12​
13**[Try the live demo](https://hackernews-realtime.vercel.app/)** ·
14**[Explore Neon](https://neon.com)** ·
15**[Neon Realtime docs](https://neon.com/docs/realtime/overview)**
16​
17Browse the top and new feeds, or open a story's comment count to follow its
18nested discussion live. Voting, replying, submitting and viewing profiles link
19to the original Hacker News site.
20​
21## Built with Neon
22​
23| Service | How this demo uses it |
24| --- | --- |
25| **Neon Realtime** | Streams live query results for story lists, story metadata, comment threads and the event timeline to the browser. |
26| **Neon Postgres** | Stores the Hacker News mirror, feed rankings, comments, event history and pending ingestion updates. |
27| **Neon Functions** | Runs the ingester, maintaining connections to the Hacker News API and writing changes into Postgres. |
28| **Neon Function Triggers** | Invokes ingestion every minute. Overlapping workers use database leases to hand off ingestion while keeping one active writer. |
29​
30Next.js and React provide the interface, Drizzle defines the database queries,
31and Vercel hosts the web app. The source data comes from the
32[official Hacker News API](https://github.com/HackerNews/API).
33​
34## How it works
35​
36```mermaid
37flowchart LR
38 HN[Hacker News API] --> Ingest[Neon Function]
39 Schedule[Neon Function Trigger] --> Ingest
40 Ingest --> DB[Neon Postgres]
41 DB --> RT[Neon Realtime]
42 RT --> Browser[React interface]
43 DB --> Next[Next.js server rendering]
44 Next --> Browser
45```
46​
47### Ingesting Hacker News
48​
49The ingester subscribes to Hacker News's Firebase feeds and item updates, with
50periodic REST reconciliation to refresh the mirror. It tracks the first 150
51items in each of the top and new feeds. Comment threads are watched while
52people have them open, with multiple viewers sharing the same upstream
53subscription.
54​
55Feed membership and complete story records are written together. A Postgres
56lease and fencing token ensure that only the active ingestion worker can
57publish, while a standby worker prepares to take over. Pending changes are
58stored in Postgres so they survive worker handoffs.
59​
60Hacker News can deliver changes in bursts. The ingester spreads updates over a
61configurable window, defaulting to 28 seconds, to give the demo a steadier flow
62of activity. This adds up to 28 seconds of delay after receiving a change.
63Initial loads happen immediately, and feed reorders and comment-tree changes
64stay atomic. Set `INGEST_SMOOTHING_MS=0` to publish updates immediately.
65​
66The ingestion implementation is in [ingest/](ingest/). The Neon Function and its
67schedule are defined in [neon.ts](neon.ts), with the Function entry point in
68[functions/ingest.ts](functions/ingest.ts).
69​
70### From SQL queries to a live interface
71​
72Next.js renders the initial stories and comments on the server. The server
73also seals each query, producing a capability that lets the browser subscribe
74to that specific query through Neon Realtime. Database credentials and the
75Realtime sealing secret stay on the server.
76​
77The queries in [lib/queries.ts](lib/queries.ts) use Drizzle and Neon's Drizzle
78adapter. One Realtime client in the root layout shares a connection across the
79feed, discussion and timeline subscriptions. Internal navigation prepares the
80destination's live queries before switching pages, and the connection stays
81open as you move around.
82​
83Feeds show 30 stories per page. Discussions load a small initial batch of
84comments, then fill in the remaining replies progressively, up to 500 comments
85per story. Replies can be collapsed, and each thread links to the full original
86discussion on Hacker News.
87​
88### Animations and the event timeline
89​
90React compares incoming rows by stable item ID to distinguish changed numbers,
91arrivals, removals and rank changes. Number changes highlight only the affected
92value; arriving rows expand and reordered rows animate to their new positions.
93​
94Postgres triggers record story, feed and comment changes in an event journal,
95inside the same transaction as each change. A separate Realtime query powers
96the footer timeline across all mirrored feeds and watched discussions.
97​
98The timeline shows two minutes on desktop and 60 seconds on mobile. Orange
99markers relate to items on screen; grey markers relate to items elsewhere.
100Items entering or leaving the viewport stay orange during their transition.
101Hover, focus or tap a marker to inspect its details. The interface also respects
102reduced-motion preferences.
103​
104## Run locally
105​
106### Prerequisites
107​
108- Node.js **22.23.2**, npm **10.9.8** and Git.
109- Access to the Neon source repository used by `npm run bootstrap`, pinned in
110 [neon-toolchain.lock.json](neon-toolchain.lock.json).
111- A Neon Postgres branch with logical replication and Realtime enabled. Allow
112 `http://localhost:3000` as a browser origin in its Realtime configuration.
113 See the [Neon Realtime docs](https://neon.com/docs/realtime/overview) for setup.
114​
115### 1. Install
116​
117```sh
118git clone https://github.com/samwillis/hackernews-realtime.git
119cd hackernews-realtime
120npm run bootstrap
121npm ci
122cp -n .env.example .env.local
123```
124​
125Bootstrap builds the pinned Neon SDK and CLI with pnpm 10.30.3 and creates the
126local packages required by `npm ci`.
127​
128### 2. Configure your branch
129​
130Fill in these values in `.env.local` using your branch's connection details:
131​
132| Variable | Value |
133| --- | --- |
134| `DATABASE_URL` | Pooled Postgres connection URL for application and ingestion queries. |
135| `DATABASE_URL_UNPOOLED` | Direct Postgres connection URL for schema setup. |
136| `NEON_REALTIME_SECRET` | Server-side secret used to seal live queries. |
137| `NEON_REALTIME_URL` | Your branch's Realtime WebSocket endpoint, starting with `wss://`. |
138| `NEXT_PUBLIC_NEON_REALTIME_URL` | The same WebSocket endpoint, exposed to the browser. |
139​
140Keep `.env.local` out of version control. Only the WebSocket endpoint belongs in
141a browser-visible environment variable.
142​
143### 3. Create the schema and load the feeds
144​
145For a new branch, run:
146​
147```sh
148npm run db:setup
149npm run seed
150```
151​
152This applies the migrations in [migrations/](migrations/) and loads real Hacker
153News stories. If your branch already has an active ingester, skip seeding and
154reuse that ingester.
155​
156### 4. Start the app and ingestion
157​
158Start Next.js:
159​
160```sh
161npm run dev
162```
163​
164In a separate terminal, start local ingestion:
165​
166```sh
167npm run ingest -- --watch
168```
169​
170Open **[localhost:3000](http://localhost:3000)**. The ingestion command repeats
171sessions while the web app serves pages and subscribes to database changes. If
172your branch already has a scheduled ingester, you only need the web app.
173​
174To disable smoothing locally, set `INGEST_SMOOTHING_MS=0` in `.env.local` and
175restart the ingestion process. The default is `28000`; accepted values range
176from `0` to `60000` milliseconds.